How to prevent overwriting output when writing to a file? [duplicate] - java

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
Sorry for the confusing title. I tried to make it as concise as possible. I am reading from an input file, parsing it, and writing to an output file. The problem I am having is once the program finishes running, the output file only contains the last item that is read from the input. Each input is being overwritten by the next. I think my problem lies in this code segment.
protected void processLine(String aLine) throws IOException {
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter(" ");
if (scanner.hasNext()){
String input = scanner.next();
PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
writer.println(input);
writer.close();
} else {
System.out.println("Empty or invalid line. Unable to process.");
}
}
Any and all help/advice is appreciated.

Just add true as a parameter to open the file in append mode
PrintWriter writer = new PrintWriter(new FileWriter("output.txt",true));
Append mode makes sure that while adding new content, the older content is retained. Refer the Javadoc

You could open the file in append mode, but it would be better not to open and close the output file every time around the loop. Open it once before you start, and close it when finished. This will be far more efficient.

Related

PrintWriter is only printing out the first line of the text file

I want the program to save each line of the text file i have into String s and print String s with a PrintWriter into another text file.
File htmltext = new File(filepath);
Scanner file = new Scanner(htmltext);
PrintWriter out = new PrintWriter("updated.txt");
while (file.hasNext()) {
String s = file.nextLine();
out.println(s);
out.close();
I've run the code and out.println(s), only printed out the first time of the text file.
I looked up how to print string into a text file and I found that I should use PrintWriter.
I was expecting the program to basically "re-print" the content of the text document into the "updated.txt" file using PrintWriter.
However, it only seems to be "re-printing" out the first line of the text file into "updated.txt".
I thought something was wrong with my while loop so I tried printing it out regularly into the console using System.out.println(s), but that worked fine.
What I understand of the while-loop is that while the file has tokens, it will iterate and s will store one line and (it should) print said string s.
What am I missing? Am I misunderstanding how the while-loop works? or how nextLine() works? or how PrintWriter works.(probably all of the above...)
I would love feedbacks!
Don't close the write object before it is finished reading the whole content
File htmltext = new File(filepath);
Scanner file = new Scanner(htmltext);
PrintWriter out = new PrintWriter("updated.txt");
while (file.hasNext())
{
String s = file.nextLine();
out.println(s);
}
**out.close();**
You're telling it to close as soon as it writes the line.
You want to move out.close to outside of your while loop, you should probably flush the stream as well.
Your code, in english, basically says:
open a scanner from stdin
open a printwriter for a file
while the scanner has a new line
write the new line to the printwriter
**close the printwriter**
After the printwriter is closed, you can't write new data, because it's closed.
Don't close the PrintWriter inside the loop. Do that after the while loop.

Output not getting as intened [duplicate]

This question already has answers here:
File Write - PrintStream append
(2 answers)
Closed 6 years ago.
I'm trying to read the file "ab.txt" and saving its content in "Output.txt" Kth times,so i'm suppose to get the content of input file K times in output file,but i'm getting only once whereas it is printing on console Kth times.
import java.io.*;
import java.util.Scanner;
class PrintStreamTest1
{
public static void main(String... l)throws IOException
{
int k=0;
long avgTime=0;
while(k<100)
{
long startTime=System.nanoTime();
String s;
Scanner fin=new Scanner(new BufferedInputStream(new FileInputStream("ab.txt")));
PrintStream output=new PrintStream("Output.txt");
while(fin.hasNextLine())
{
s=fin.nextLine();
System.out.println(s);
output.print(s+"\n");
}
avgTime=avgTime+((System.nanoTime()-startTime)/10000000);
fin.close();
output.close();
k++;
}
System.out.println("\n "+ avgTime+"ms");
}
}
You are using the wrong constructor as you can see in the Javadoc :
PrintStream(String fileName)
...
fileName The name of the file to use as the destination of this print stream. If the file exists, then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
You should open the file associated with the PrintStream in append mode if you don't want the content of that file overwritten in each iteration of your loop :
PrintStream output = new PrintStream(new FileOutputStream("Output.txt",true));
Alternately, just open the file once before the loop and close it once after the loop.

Java-How to insert a string to certain line, say line6, of a txt file [duplicate]

This question already has answers here:
Inserting text into an existing file via Java
(8 answers)
Closed 9 years ago.
I want to insert a line into a specific location of a .txt file. Now the only way I know is to read out the whole file out as an array, put the given line in the correct place and then write the whole thing back. Is there an easier way to achieve this using Java? My intention is to reduce the file access as much as possible.
Is there an easier way to achieve this using Java?
With Java 7, unless your insertion point is towards the end of a huge file, I would simply do:
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);
Try to read and write at the same time by using BufferedReader.
The Idea is to read line and immediately write it to other file.
BufferedReader rd = null;
BufferedWriter wt = null;
try {
rd = new BufferedReader(
new InputStreamReader(
new FileInputStream("/yourfile.txt"), "UTF-8")
);
wt = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(
"/newfile" + ".txt"), "UTF-8")
);
int count = 0;
for (String line; (line = reader.readLine()) != null;) {
count++
if (count == 6) {
// add your line
// wt.write(newline);
}
wt.write(line);
wt.newLine();
}
} finally {
close(wt);
close(rd);
}
RandomAccessFile do not solve this problem. It was discussed in this post. You should rewrite file anyway.
You can only read and write it with some buffer, alter it and immidiate write to new to save your program memory.

Small input trouble in a program in java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have learnt about BufferedReader as well as BufferedWriter, so I decided to create a small text processor for the command line (meaning without interface, just in cmd/terminal). It asks a user for document name (Which will then create a file) and then user can type sentences. Each time user presses "enter" button, text is entered into the file and new line is created and then allowing user to type more. At the end, it will display a message saying file is created.
NOW, I have encountered a problem where user would not be able to stop the process of entering data and creating file, because the program kept creating new lines despite entering nothing or quit keyword(which i stated in the code in order to quit the program.)
Here is my original code:
import java.io.*;
class TextProcessor
{
public static void main(String[] args)
{
try
{
System.out.println("Please enter name of the file");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //User input
String file = in.readLine();
BufferedWriter writer = new BufferedWriter(new FileWriter(file)); //Creating file as well as instance for inputting text to the file.
System.out.println("Enter text");
String line = "";
do
{
line = ins.readLine();
System.out.println(line);
writer.write(line);
System.out.println("Second " + line);
writer.newLine();
}
while(line != "quit()");
//while(line != null);
in.close();
writer.close();
System.out.println("Text is created with entered text");
}
catch(IOException e)
{
System.out.println("Error occured");
}
}
}
However, I found a solution to this, which is replacing do-while block with while one:
int counter = 0;
while(counter != 1)
{
line = in.readLine();
writer.write(line);
if(line.equals("quit()"))
{
++counter;
}
else {writer.newLine();}
}
I have a question about this now, why can't I use do-while statement instead of while, even if it seems logical that the program would work? Thank you for reading this!!!!
P.S. I also wonder if I can bring small improvements to this or any other way creating this type of program. Thanks if you give feedback!
Probably the error asked about the most.
Answer can be found here: How do I compare strings in Java?
while(line != "quit()");
must be
while(!line.equals("quit()"));

Java remove complete line from file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java - Find a line in a file and remove
I am trying to remove a complete line from a text file, and have managed to remove the line if there is only one single unbroken line of text without spaces. If i have a space delimiter between strings it fails to remove anything.
Code as follows:
import java.io.*;
import java.util.Scanner;
public class removebooks {
// construct temporary file
public static void main(String[]args)throws IOException {
String title;
Scanner titlerem= new Scanner (System.in);
System.out.println("Enter Title to remove from file");
title = titlerem.next ();
// construct temporary file
File inputFile = new File("books.txt");
File tempFile = new File(inputFile + "temp.txt");
BufferedReader br = new BufferedReader (new FileReader("books.txt"));
PrintWriter Pwr = new PrintWriter(new FileWriter (tempFile));
String line = null;
//read from original, write to temporary and trim space, while title not found
while((line = br.readLine()) !=null) {
if(line.trim().equals(title)){
continue; }
else{
Pwr.println(line);
Pwr.flush();
}
}
// close readers and writers
br.close();
Pwr.close();
titlerem.close();
// delete book file before renaming temp
inputFile.delete();
// rename temp file back to books.txt
if(tempFile.renameTo(inputFile)){
System.out.println("Update succesful");
}else{
System.out.println("Update failed");
}
}
}
the text file is called books.txt and contents simply should look like:
bookone author1 subject1
booktwo author2 subject2
bookthree author3 subject3
bookfour author4 subject4
thank you any help would be appreciated
Why don't you use
if(line.trim().startsWith(title))
instead of
if(line.trim().equals(title))
because equals() is only true if both strings are equal, and startsWith() is true if line.trim() starts with title ;)
As you are reading the file line by line. You can make use of following
if(line.contains(title)){
// do something
}
In this case you will not be limited by title only.
String API
br.readLine() sets the value of variable line to "bookone author1 subject1".
Scanner.next() delimits by whitespace. You need to consolidate all your calls to Scanner.next() to a single String before checking against the lines in the file, if that is your intent.
In your case, if you typed "bookone author1 subject1", value of variable title would be "bookone" after your call to Scanner.next().

Categories