0

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

谢谢

4

2 回答 2

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();
  }
}

如果您明确希望整个文件在内存中,您还可以将输入包装在 a 中DataInputStream,并在使用后使用readFully(byte[])File.length()来计算文件的大小。

于 2013-06-03T10:19:05.823 回答
0

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

这里有一些针对不同 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");
    }
于 2013-06-03T10:27:40.390 回答