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();
}
Related
I have tried using writer.newLine() however it says method not found. Does anyone know how I can write a new line after each iteration?
public static void keepLetters() throws IOException {
BufferedReader sourceReader = new BufferedReader(new FileReader("input.txt"));
for (String line = sourceReader.readLine(); line != null; line = sourceReader.readLine()) {
String updatedLine = line.replaceAll("[^A-Za-z]", "");
System.out.println(updatedLine);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("output.txt"), "UTF-8"))) {
writer.write(updatedLine);
}
}
}
I wrote writer.nextLine() after writer.write(updatedLine);
Thank you
The correct method is newLine(), but you need to call it on a BufferedWriter, not a Writer.
Like so:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("output.txt", true), "UTF-8"))) {
writer.write(updatedLine);
writer.newLine();
}
Note this part try (BufferedWriter writer
Update for comment
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8"));
for (int i = 0; i < linesToWrite; i++){
writer.write(updatedLine);
writer.newLine();
}
writer.close();
You can simple do
writer.write(updatedLine + "\n");
which will ensure a newline is written after every updatedLine.
EDIT:
The writer is being reinitiated to the same file output every iteration of the loop. It should be initialised once before the loop and closed later on to resolve your issue.
I'm trying to edit an existing file that I had just created and so far I have no clue on how it's done.
Can anyone show me how and please explain line by line on what the code does?
import java.io.*;
public class Hey {
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Title");
String title = br.readLine();
File f = new File(title +".txt");
f.createNewFile();
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("What you want to input in the text");
String text = br.readLine();
bw.write(text);
bw.flush();
bw.close();
}
}
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
Creates a read buffer from the standard input.
String title = br.readLine();
Reads from this buffer until there's a return character sequence found ('\n', '\r' or "\r\n"). The entire line excluding the return sequence will be saved as title.
File f = new File(title +".txt");
Creates a File object with the name read from the console.
f.createNewFile();
Creates the file if it doesn't exist yet.
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
Creates a buffered writer to write into fw.
String text = br.readLine();
Again reads a line from the console.
bw.write(text);
Writes this line into the buffer.
bw.flush();
Ensures the whole buffer is flushed into the file (written into the file).
bw.close();
Closes the buffer of your buffered writer. You should also close the reader buffer br and the FileWriter fw.
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")));
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
This is code i Have written instead of editing a particular line new name gets appened at the last...
please help me out....
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter("d:\\book.txt", true)));
BufferedReader br = null;
FileReader reader = null;
try {
reader = new FileReader("d:\\book.txt");
br = new BufferedReader(reader);
String line;
System.out.println((";;;;;;;;;;;;;;;;" + request
.getParameter("hname")));
System.out.println(request.getParameter("book"));
while ((line = br.readLine()) != null) {
if (request.getParameter("hname").equals(line)) {
line = line.replace(request.getParameter("hname"),
request.getParameter("book"));
writer.println(line);
writer.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
reader.close();
}
Unless you aren't changing the (byte) length of the line, you need to rewrite the whole file, adding the changed line where appropriate. This is actually just a simple change from your current code. First, initialize your FileWriter without the append (since you don't want to just append to the end of the file, which is what you're doing now).
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.txt")));
Then, either read the whole file into memory (if the file is small enough) or else write a temp file as you go and then copy it over when you're done. The second way is more robust, and requires less code changing; just modify your while loop to write every line, modified or not.
// Open a temporary file to write to.
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("d:\\book.temp")));
// ... then inside your loop ...
while ((line = br.readLine()) != null) {
if (request.getParameter("hname").equals(line)) {
line = line.replace(request.getParameter("hname"),
request.getParameter("book"));
}
// Always write the line, whether you changed it or not.
writer.println(line);
}
// ... and finally ...
File realName = new File("d:\\book.txt");
realName.delete(); // remove the old file
new File("d:\\book.temp").renameTo(realName); // Rename temp file
Don't forget to close all your file handles when you're done!