写入不同的文件而不是覆盖文件

时间:2013-06-03 10:11:12

标签: java

我想知道java中是否有选项可以从特定路径读取文件,即C:\test1.txt更改内存中文件的内容并将其复制到D:\test2.txt,同时{{1}的内容不会更改,但受影响的文件将为C:\test1.txt

由于

2 个答案:

答案 0 :(得分:1)

作为基本解决方案,您可以从一个FileInputStream中读取数据并写入FileOutputStream

import java.io.*;
class Test {
  public static void main(String[] _) throws Exception{
    FileInputStream inFile = new FileInputStream("test1.txt");
    FileOutputStream outFile = new FileOutputStream("test2.txt");

    byte[] buffer = new byte[128];
    int count;

    while (-1 != (count = inFile.read(buffer))) {
      // Dumb example
      for (int i = 0; i < count; ++i) {
        buffer[i] = (byte) Character.toUpperCase(buffer[i]);
      }
      outFile.write(buffer, 0, count);
    }

    inFile.close();
    outFile.close();
  }
}

如果您明确要将整个文件放在内存中,您也可以使用DataInputStream将输入包装在File.length()中并使用readFully(byte[])来计算文件的大小。< / p>

答案 1 :(得分:0)

我认为,最简单的方法是使用Scanner class来读取文件,然后使用writer编写。

Here are some nice examples用于不同的java版本。

或者,您也可以使用apache commons lib来读/写/复制文件。

public static void main(String args[]) throws IOException {
        //absolute path for source file to be copied
        String source = "C:/sample.txt";
        //directory where file will be copied
        String target ="C:/Test/";

        //name of source file
        File sourceFile = new File(source);
        String name = sourceFile.getName();

        File targetFile = new File(target+name);
        System.out.println("Copying file : " + sourceFile.getName() +" from Java Program");

        //copy file from one location to other
        FileUtils.copyFile(sourceFile, targetFile);

        System.out.println("copying of file from Java program is completed");
    }
相关问题