Reputation: 11
I want to take the content of one text file chosen by the user and add it to another text file without replacing the current content. So for example:
Update: How do I add it to the second file in a numbered way?
TextFile1:
AAA BBB CCC
AAA BBB CCC
TextFile2: (After copying)
EEE FFF GGG
AAA BBB CCC
AAA BBB CCC
Update: I had to remove my code as it may be taken for plagiarism, This was answered so I know what to do, thanks for everyone helping me out.
Upvotes: 1
Views: 1653
Reputation: 2288
Try this You have to use
new FileWriter(fileName,append);
This opens the file in append mode:
According to the javadoc it says
Parameters: fileName String The system-dependent filename.
append boolean if true, then data will be written to the end of the file rather than the beginning.
public static void main(String[] args) {
FileReader Read = null;
FileWriter Import = null;
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
Read = new FileReader(filename);
Import = new FileWriter("songstuff.txt",true);
int Rip = Read.read();
while(Rip!=-1) {
Import.write(Rip);
Rip = Read.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(Read);
close(Import);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
// JavaProgram();
}
}
Upvotes: 2
Reputation: 1552
A file channel that is open for writing may be in append mode .. http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html
also have a look at .. http://docs.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)
Upvotes: 0
Reputation: 17461
You can use Apache commons IO.
Example:
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.io.FileUtils;
public class HelpTest {
public static void main(String args[]) throws IOException, URISyntaxException {
String inputFilename = "test.txt"; // get from the user
//Im loading file from project
//You might load from somewhere else...
URI uri = HelpTest.class.getResource("/" + inputFilename).toURI();
String fileString = FileUtils.readFileToString(new File(uri));
// output file
File outputFile = new File("C:\\test.txt");
FileUtils.write(outputFile, fileString, true);
}
}
Upvotes: 1
Reputation: 2871
Use new FileWriter("songstuff.txt", true);
to append to the file instead of overwriting it.
Refer : FileWriter
Upvotes: 1
Reputation: 8466
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
new FileWriter(fileName,true);
Upvotes: 0