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

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.

Related

Reading data from a csv file and storing into an array, my file opens correctly however the file is being read incorrectly

String fileName = "MSFT.csv";
File file = new File(fileName);
try{
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext()){
String data = inputStream.next();
System.out.println(data);
}
inputStream.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
I am attempting to read from a csv file and when I run this code to make sure the file is being read correctly all of the comma separated data displays correctly with the exception of the first line. The first line from the file is being output with each word being on a different line. What am I doing wrong with my initial reading of the file?
An example of my output goes as:
Timestamp,
close,
high,
low,
open,
value,
9:30,57.515,57.57,57.47,57.515,31120
Now all of my words in this case are on the same line in the excel file, but when I run it timestamp, close, high, etc all appear on different lines so I'm not sure why it appears like this.
The Scanner hasNext is defined as follows:
hasNext() Returns true if this scanner has another token in its input.
So when you use it your are reading your csv file token by token and not line by line. Beside that using the Scanner next does the following:
next() Finds and returns the next complete token from this scanner.
And finally using System.out.println will insert a line separator after printing your data, which is why it keeps going to the next line after outputing each token.
Change your code as follows and it should work as expected:
String fileName = "MSFT.csv";
File file = new File(fileName);
try{
Scanner inputStream = new Scanner(file);
while(inputStream.hasNextLine()){
String data = inputStream.nextLine();
System.out.println(data);
}
inputStream.close();
} catch(FileNotFoundException e){
e.printStackTrace();

Why does introducing a FileWriter delete all the content in the file?

I have a text file with some text in it and i'm planning on replacing certain characters in the text file. So for this i have to read the file using a buffered reader which wraps a file reader.
File file = new File("new.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
But since i have to edit characters i have to introduce a file writer and add the code which has a string method called replace all. so the overall code will look as given below.
File file = new File("new.txt");
FileWriter fw = new FileWriter(file);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
fw.write(br.readLine().replaceAll("t", "1") + "\n");
}
Problem is when i introduce a file writer to the code (By just having the initialization part and when i run the program it deletes the content in the file regardless of adding the following line)
fw.write(br.readLine().replaceAll("t", "1") + "\n");
Why is this occurring? am i following the correct approach to edit characters in a text file?
Or is there any other way of doing this?
Thank you.
public FileWriter(String fileName,
boolean append)
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the
file rather than the beginning.
To append data use
new FileWriter(file, true);
The problem is that you're trying to write to the file while you're reading from it. A better solution would be to create a second file, put the transformed data into it, then replace the first file with it when you're done. Or if you don't want to do that, read all of the data out of the file first, then open it for writing and write the transformed data.
Also, have you considered using a text-processing language solution such as awk, sed or perl: https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files
You need to read the file first, and then, only after you read the entire file, you can write to it.
Or you open a different file for writing and then afterwards you replace the old file with the new one.
The reason is that once you start writing to a file, it is truncated (the data that was in the file is deleted).
The only way to avoid that is to open the file in "append" mode. With that mode, you start writing at the end of the file, so you don't delete its content. However, you won't be able to modify the existing content, you will only add content.
Maybe like this
public static void main(String[] args) throws IOException {
try {
File file = new File("/Users/alexanderkrum/IdeaProjects/printerTest/src/atmDep.txt");
Scanner myReader = new Scanner(file);
ArrayList<Integer> numbers = new ArrayList<>();
while (myReader.hasNextLine()) {
numbers.add(myReader.nextInt() + 1);
}
myReader.close();
FileWriter myWriter = new FileWriter(file);
for (Integer number :
numbers) {
myWriter.write(number.toString() + '\n');
}
myWriter.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Just add at last :
fw.close();
this will close it ,then it will not delete anything in the file.
:)

Remove new line character from the middle of a file line in java

I would like to remove the new line character in the middle of a line of a file while it is reading the file.
If I'm going to read the file with BufferedReader then it is recognised as a new line and split the line in the middle. I want to be able to read the file and remove those new line characters of the middle while reading.
The format of each line is a simple Json.
Thank you
If what youre saying is you want to remove the newlines from the original file after reading them, I think you can just write to a new (temporary) file while youre reading the lines, and then replace the file with the original after youre done writing.
If I'm interpreting your question correctly, what you want to do isn't quite as simple as "read and write at the same time". What you need is a loop and a StringBuilder.
public String readFileWithNoLines(BufferedReader reader) throws IOException {
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
Then you want to write the return value of that function to the file.

How to go back to the first line in a text file without reading it again?

I wrote this code and I think I went to the last line of the code while using line=input.nextLine(). Now I don't know how do I get back to the first line of the text file again. I am not allowed to read the file again.
File file = new File(fileName);
input = new Scanner(file);
bufRdr = new BufferedReader(new FileReader(file));
this.cols=bufRdr.readLine().length();
while (input.hasNext()){
this.rows++;
line=input.nextLine();
}
theMaze=new char[this.rows][this.cols];
int i=0;
while(i<this.rows){
line=input.nextLine();
for (int j=0;j<this.cols;j++){
theMaze[i][j]=line.charAt(j);
}
i++;
}
} catch(Exception e){
System.out.println("Error......" +e.getMessage());
}
You have to use RandomAccessFile and use seek to get to the top. BufferedReader reads sequentially; you cannot jump. You should check mark method of BufferedReader.
You don't need to. Instead of a 2-dimensional array of characters, you should use an ArrayList of Strings. ArrayLists can grow on demand, so with them, you only need to read through the file once - you don't need to count the number of lines first:
ArrayList<String> lines = new ArrayList<String>();
while (input.hasNext()) {
lines.add(input.nextLine());
}

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

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.

Categories