Blue Label
Blue Label

Reputation: 437

Write to different file instead of overwriting file

I am wondering if there is an option in java to read file from specific path i.e C:\test1.txt change the content of the file in the memory and copy it to D:\test2.txt while the content of C:\test1.txt will not change but the affected file will be D:\test2.txt

Thanks

Upvotes: 0

Views: 104

Answers (2)

terafor
terafor

Reputation: 1626

I think, the easiest you can do, is to use Scanner class to read file and then write with writer.

Here are some nice examples for different java versions.

Or, you can also use apache commons lib to read/write/copy file.

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

Upvotes: 0

Vlad
Vlad

Reputation: 18633

As a basic solution, you can read in chunks from one FileInputStream and write to a 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();
  }
}

If you explicitly want the entire file in memory, you can also wrap your input in a DataInputStream and use readFully(byte[]) after using File.length() to figure out the size of the file.

Upvotes: 1

Related Questions