I need to open an existing file for appending and create new file for appending if it doesn't exist.
I tried PrintWriter function but it always create a new file and deletes the old. So could you help me? What should I use for that?
UPD: That's what I already tried
writer = new PrintWriter(System.getProperty("db.file"), "UTF-8");
writer.println("The first line");
Try this
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("your_file.txt", true)));
The true parameter of FileWriter indicates it has to append data.
To add specify encoding you can use
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("your_file.txt", true), "UTF-8")));
Related
Java Gradle project
File saving in build/resources, but reading from src/resources
Does anyone know how to save and read from the same directory?
below is my code for writing:
File file = new File((this.getClass().getClassLoader().getResource("test.txt")).toURI());
FileWriter fw = new FileWriter(file, false);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
pw.println("test");
pw.close();
below is my code for reading:
BufferedReader br = new BufferedReader(new FileReader(new File((this.getClass().getClassLoader().getResource("test.txt")).toURI())));
String amount = br.readLine();
I have a server that writes to a logfile, but I do not want to append lines. I have set the flag to false, but still it seems to be appending. How can I make it REPLACE the first line everytime so my file contains one updated line everytime ?
fos = new FileOutputStream(new File(filename), false);
PrintWriter bw = new PrintWriter(new OutputStreamWriter(fos));
..
..
while(true){
line = getRandomLine();
bw.println(line);
bw.flush();
}
..
..
If I understand You correctly, you want this:
File file = new File(filename);
while (true) {
pw = new PrintWriter(file);
line = getRandomLine();
pw.println(line);
pw.flush();
pw.close();
}
I have an application that reads a file then a user updates the file with different language and saves it. But whenever anyone changes the language and saves the txt file change the letters into symbols ??? I think i have to save it as utf-8 formatted. Any idea?
The next part of code where i get the data from a jtable and save it to a file when user click at save button.
Note: there is nothing wrong with the code. The problem is that the file has to be saved as utf-8.
if(buttonPressed.equals(save)){
File myFile = new File("youFile.srt");
try (PrintWriter writer = new PrintWriter(myFile)) {
for (int i =0 ; i< cModel.getRowCount(); i++)
{
sData.add(cModel.getValueAt(i, 1).toString());
eData.add(cModel.getValueAt(i, 2).toString());
tData.add(cModel.getValueAt(i, 3).toString());
writer.println(i+1 + "\n");
writer.println(sData.get(i)+" --> " + eData.get(i));
writer.println(tData.get(i));
writer.println("\n");
}
}catch(FileNotFoundException ioEx){
ioEx.printStackTrace();
}
PrintWriter need to be clubbed with OutputStreamWriter because it offers constructors to provide the file format. Here is what you can do:
FileOutputStream outputStream = new FileOutputStream(myFile);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(
outputStream, StandardCharsets.UTF_8), true)
You are using a FileWriter. It is better to create a FileOutputStream and then use OutputStreamWriter to write the output. OutputStreamWriter allows you to specify the encoding.
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("youFile.srt"), "UTF-8"));
try {
writer.write(aString);
} finally {
writer.close();
}
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 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.