【问题标题】:Appending multiple files into one将多个文件合并为一个
【发布时间】:2012-10-15 11:25:19
【问题描述】:

我在某些位置有 4 个不同的文件,例如: D:\1.txt D:\2.txt D:\3.txt 和 D:\4.txt

我需要创建一个新文件为NewFile.txt,它应该包含上述文件1.txt、2.txt、3.txt 4.txt中存在的所有内容... ....

所有数据都应该出现在新的单个文件(NewFile.txt)中..

请建议我在 java 或 Groovy 中做同样的事情......

【问题讨论】:

    标签: java string file groovy


    【解决方案1】:
    public static void main(String[] args) throws IOException {
        List<String> files=new ArrayList<String>();
    
            for(int i=10;i<14;i++)
                files.add("C://opt/Test/test"+i+".csv");
    
        String destFile ="C://opt/Test/test.csv";
        System.out.println("TO "+destFile);
        long st=System.currentTimeMillis();
        mergefiles(files, destFile);
        System.out.println("DONE."+(st-System.currentTimeMillis()));
    }
    
    public static void mergefiles(List<String> files,String destFile){
        Path outFile = Paths.get(destFile);
        try(FileChannel out=FileChannel.open(outFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
              for(String file:files) {
                Path inFile=Paths.get(file);
                System.out.println(inFile);
                try(FileChannel in=FileChannel.open(inFile, StandardOpenOption.READ)) {
                  for(long p=0, l=in.size(); p<l; )
                    p+=in.transferTo(p, l-p, out);
                }catch (IOException e) {
                     System.out.println("ERROR:: "+e.getMessage());
                }
                out.write(ByteBuffer.wrap("\n".getBytes()));
              }
            } catch (IOException e) {
                 System.out.println("ERROR:: "+e.getMessage());
            }
    }
    

    【讨论】:

    • 欢迎来到 Stack Overflow。答案只是代码?你能编辑一个解释吗? How to Answer。谢谢。
    【解决方案2】:

    我尝试解决这个问题,如果将内容复制到数组并将数组写入不同的文件,我发现它非常容易

    public class Fileread 
    {
    
    public static File read(File f,File f1) throws FileNotFoundException
    {
    
        File file3=new File("C:\\New folder\\file3.txt");
        PrintWriter output=new PrintWriter(file3);
        ArrayList arr=new ArrayList();
        Scanner sc=new Scanner(f);
        Scanner sc1=new Scanner(f1);
        while(sc.hasNext())
        {
            arr.add(sc.next());
    
        }
         while(sc1.hasNext())
        {
            arr.add(sc1.next());
    
        }
           output.print(arr);
       output.close();
    
        return file3;
    }
    /**
     *
     * @param args
     * @throws FileNotFoundException
     */
    public static void main(String[] args) {
        try
        {
       File file1=new File("C:\\New folder\\file1.txt");
       File file2=new File("C:\\New folder\\file2.txt");
       File file3=read(file1,file2);
       Scanner sc=new Scanner(file3);
       while(sc.hasNext())
           System.out.print(sc.next());
    
        }
        catch(Exception e)
        {
            System.out.printf("Error  :%s",e);
        }
    }
    }
    

    【讨论】:

      【解决方案3】:

      一个班轮示例:

      def out = new File(".all_profiles")
      ['.bash_profile', '.bashrc', '.zshrc'].each {out << new File(it).text}
      

      ['.bash_profile', '.bashrc', '.zshrc'].collect{new File(it)}.each{out << it.text}
      

      如果你有大文件,Tim 的实现会更好。

      【讨论】:

        【解决方案4】:

        我正在向您展示它在 java 中的完成方式:

        public class Readdfiles {
          public static void main(String args[]) throws Exception
          {
            String []filename={"C:\\WORK_Saurabh\\1.txt","C:\\WORK_Saurabh\\2.txt"};
            File file=new File("C:\\WORK_Saurabh\\new.txt");
            FileWriter output=new FileWriter(file);
            try
            {   
              for(int i=0;i<filename.length;i++)
              {
                BufferedReader objBufferedReader = new BufferedReader(new FileReader(getDictionaryFilePath(filename[i])));
        
                String line;
                while ((line = objBufferedReader.readLine())!=null )
                {
                  line=line.replace(" ","");
        
                  output.write(line);
                }
                objBufferedReader.close();
              }
              output.close();
            }
            catch (Exception e) 
            {
              throw new Exception (e);
            }
          }
        
          public static String getDictionaryFilePath(String filename) throws Exception
          {
            String dictionaryFolderPath = null;
            File configFolder = new File(filename);
            try 
            {
              dictionaryFolderPath = configFolder.getAbsolutePath();
            } 
            catch (Exception e) 
            {
              throw new Exception (e);
            }
            return dictionaryFolderPath;
          }
        }
        

        如果您有任何疑问,请告诉我

        【讨论】:

        • 为什么要捕获异常,然后再次将其作为新的(更通用的)异常抛出?另外,如果抛出异常,这不能保留打开的文件句柄(如果代码被获取并放入通用函数中)?
        • 实际上这是我实施的一个更大项目的一部分。我编写了一个新程序,从执行此特定部分的模块中提取部分内容。在我的实际项目中,这个主函数是一个单独的函数,它在另一个函数中被调用。
        【解决方案5】:

        您可以在 Java 中执行类似的操作。希望它可以帮助您解决问题:

        import java.io.*;
        class FileRead {
        public void readFile(String[] args) {
        for (String textfile : args) {
        
        try{
              // Open the file that is the first 
              // command line parameter
              FileInputStream fstream = new FileInputStream(textfile);
              // Get the object of DataInputStream
              DataInputStream in = new DataInputStream(fstream);
              BufferedReader br = new BufferedReader(new InputStreamReader(in));
              String strLine;
              //Read File Line By Line
              while ((strLine = br.readLine()) != null)   {
              // Print the content on the console
              System.out.println (strLine);
        
            // Write to the new file
              FileWriter filestream = new FileWriter("Combination.txt",true);
              BufferedWriter out = new BufferedWriter(filestream);
              out.write(strLine);
              //Close the output stream
              out.close();
        
              }
              //Close the input stream
              in.close();
                }catch (Exception e){//Catch exception if any
              System.err.println("Error: " + e.getMessage());
              }
        }
        }
        
         public static void main(String args[]) {
         FileRead myReader = new FileRead();
         String fileArray[] = {"file1.txt", "file2.txt", "file3.txt", "file4.txt"};
            myReader.readFile(fileArray);
        
          }
        }
        

        【讨论】:

          【解决方案6】:

          这是在 Groovy 中执行此操作的一种方法:

          // Get a writer to your new file
          new File( '/tmp/newfile.txt' ).withWriter { w ->
          
            // For each input file path
            ['/tmp/1.txt', '/tmp/2.txt', '/tmp/3.txt'].each { f ->
          
              // Get a reader for the input file
              new File( f ).withReader { r ->
          
                // And write data from the input into the output
                w << r << '\n'
              }
            }
          }
          

          这样做的好处是(在每个源文件上调用getText)是它不需要在将其内容写入newfile 之前将整个文件加载到内存中。如果您的一个文件很大,则另一种方法可能会失败。

          【讨论】:

          • File 也定义了#leftShift,所以你也可以使用src.inject(new File(dst)) { out, it -&gt; new File(it).withInputStream { out &lt;&lt; it } }。我相信这会打开和关闭每个源文件的目标文件,如果您要处理许多小文件,这可能是个问题。
          【解决方案7】:

          这是在 groovy 中

          def allContentFile = new File("D:/NewFile.txt")
          def fileLocations = ['D:/1.txt' , 'D:/2.txt' , 'D:/3.txt' , 'D:/4.txt']
          fileLocations.each{ allContentFile.append(new File(it).getText()) }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-04-13
            • 2012-10-19
            • 2015-01-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多