This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java append to file
How to append data to a file?
I want to write a file in java without cleaning(deleting) older data
This is my try, but the current data will be cleaned on writing new data.
import java.io.*;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "New content to write to file";
File file = new File("/mypath/filename.txt");
// if file doesnt exists, then create it
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use constructor FileWriter(String filename, boolean append) that can instruct the file to be opened in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
//^^^^ means append
Try
FileWriter fw = new FileWriter(file, true);
Notes: second param means append; no need for file.getAbsoluteFile(), just File is OK
open the file in append mode .
like
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
FileWriter takes a boolean argument which specifies whether to overwrite or not.
Try this :
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
also visit :
http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter%28java.io.File,%20boolean%29
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java append to file
How to append data to a file?
I want to write a file in java without cleaning(deleting) older data
This is my try, but the current data will be cleaned on writing new data.
import java.io.*;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "New content to write to file";
File file = new File("/mypath/filename.txt");
// if file doesnt exists, then create it
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use constructor FileWriter(String filename, boolean append) that can instruct the file to be opened in append mode:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
//^^^^ means append
Try
FileWriter fw = new FileWriter(file, true);
Notes: second param means append; no need for file.getAbsoluteFile(), just File is OK
open the file in append mode .
like
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
FileWriter takes a boolean argument which specifies whether to overwrite or not.
Try this :
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
also visit :
http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter%28java.io.File,%20boolean%29
I have this code:
for (Record record : Adatok) {
//System.out.println(record.toString2());
act_data=tmp.testtestclass(record);
System.out.println("*******");
System.out.println("Feldolgozás eredménye:");
System.out.println(data_restructure(act_data));
// String content = record.nev + ";" + record.address + "\n"+"asd";
File file = new File("resultset.csv");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data_restructure(act_data) + "\n");
bw.close();
}
My problem is that this loop running time is hours and can be interupting. So I do this filewrite/bufferedwrite in it.
So everytime he get data back than I want to write it to file.
But when I do this it is always write only 1 line to my file than nothing.
How can I improve it? I tried with firewriter, bufferedwriter but It kinda bugging.
I know its a dumb question but I cant figurit out how to solve it cause the basic examples does not works.
You can try to use FileWriter with TRUE parameter:
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true); //see here!
BufferedWriter bw = new BufferedWriter(fw);
By doing this, new Text will be appended to the file.
Put these lines outside (before) the loop. You are overwriting the file in each loop iteration.
File file = new File("resultset.csv");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
Also,
bw.close(); // outside (after) the loop
I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D
I searched the web and found this code, but I understand 50% of it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With Java 7 and up, a one liner using Files:
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
You could do this by using JAVA 7 new File API.
code sample:
`
public class FileWriter7 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
writeSmallTextFile(lines, filepath);
}
private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, StandardCharsets.UTF_8);
}
}
`
You can use FileUtils from Apache Commons:
import org.apache.commons.io.FileUtils;
final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
Appending the file FileWriter(String fileName,
boolean append)
try { // this is for monitoring runtime Exception within the block
String content = "This is the content to write into file"; // content to write into the file
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here
// if file doesnt exists, then create it
if (!file.exists()) { // checks whether the file is Exist or not
file.createNewFile(); // here if file not exist new file created
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
bw.write(content); // write method is used to write the given content into the file
bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
System.out.println("Done");
} catch (IOException e) { // if any exception occurs it will catch
e.printStackTrace();
}
Your code is the simplest. But, i always try to optimize the code further. Here is a sample.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
bw.write("Hello, This is a test message");
bw.close();
}catch (FileNotFoundException ex) {
System.out.println(ex.toString());
}
Files.write() the simple solution as #Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.
So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)
List<String> lines = Arrays.asList(new String[] { "line1", "line2" });
Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(lines.stream()
.reduce((sum,currLine) -> sum + "\n" + currLine)
.get());
}
In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
In Java 11 or Later, writeString can be used from java.nio.file.Files,
String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content);
With Options:
Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
More documentation about the java.nio.file.Files and StandardOpenOption
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));
IOUtils also can be used to write/read files easily with java 8.
I'm trying to create an error report in Java, but the file reader writes over the same line
every time I find a new error, so all that displays is the last error. How would I prevent this?
public void errorReport(String error)
{
try {
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
pw.write(error);
pw.close();
} catch (IOException e)
{
e.printStackTrace();
}
} // end error report
FileWriter fw = new FileWriter(file, true);
The second argument is "append mode." If it is true, then the FileWriter will append lines instead of writing over them.
Documentation
I want to write to a temporary file in an append mode. I see that the file is created but the data from the Stringbuffer is not getting written to it. Can somebody tell me why? Please find below the code I have written,
public static void writeToFile(String pFilename, StringBuffer sb)
throws IOException {
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
File dir = new File(tempDir);
File filename = File.createTempFile(pFilename, ".tmp", dir);
FileWriter fileWriter = new FileWriter(filename.getName(), true);
System.out.println(filename.getName());
BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(sb.toString());
bw.close();
}
This works:
public static void writeToFile(String pFilename, StringBuffer sb) throws IOException {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File tempFile = File.createTempFile(pFilename, ".tmp", tempDir);
FileWriter fileWriter = new FileWriter(tempFile, true);
System.out.println(tempFile.getAbsolutePath());
BufferedWriter bw = new BufferedWriter(fileWriter);
bw.write(sb.toString());
bw.close();
}
Note the usage of FileWriter(File, boolean) and of System.out.println(tempFile.getAbsolutePath()).
FileWriter fileWriter = new FileWriter(filename.getName(), true);
should be
FileWriter fileWriter = new FileWriter(filename, true);
Instead of creating file in temp directory , create the file in your working directory and use objFile.deleteOnExit().It will also work the same as creating file in temp dir.
Try to call bw.flush() before closing the writer. Although I think that writer should call flush automatically before being closed...
FileWriter fileWriter = new FileWriter(filename.getName(), true);
should be
FileWriter fileWriter = new FileWriter(filename, true);
you can also use this
FileWriter fileWriter = new FileWriter(filename.getAbsolutePath+filename.getName(), true);
note
`filename.getName();`
returns the filename without the absolute path. So there might be the case that it is creating a file in the Present working directory and writing into it.