Re-Writing to java txt files
i was wondering if there was a way to add to text files already created. because when i do this on an already created file:
public Formatter f = new Formatter("filename.txt");
it re-writes the current fi开发者_运维技巧lename.txt with a blank one. thanks, Quinn
Yes, use the constructor with an OutputStream
argument instead of a File
argument. That way you can open an OutputStream in append mode and do your formatting on that. Link
Try using the constructor for Formatter
which takes an Appendable
as an argument.
There are several classes which implement the Appendable
interface. The most convenient, in your case, should be FileWriter
.
This FileWrite constructor will let you open a file (whose name is specified as a String), in append mode.
Use FileOutputStream
with append boolean value as true eg new FileOutputStream("C:/concat.txt", true));
Example
public class FileCOncatenation {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/concat.txt", true));
File file2 = new File("C:/Text/file2.rxt");
System.out.println("Processing " + file2.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(file2
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
// }
pw.close();
System.out.println("All files have been concatenated into concat.txt");
}
}
精彩评论