BufferedWriter newLine method not found - java

I'm trying to get a BufferedWriter to print several Strings, each on a different Line in a text file. I'm trying to use out.newLine() to set a new line for the next string, but I'm getting an error message of cannot find symbol - method newLine()
This is the code I am trying to use:
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(start+"2"+dest+".txt"), "utf-8")); // create output file from start names
out.write(outputOne);//Write Line 1
out.newLine();
out.write(outputTwo); //Write Line 2
out.newLine();
out.write(outputThree); //Write Line 3
out.newLine();
out.write(outputFour); //Write Line 4
out.close();
} catch (IOException ex) { //Handle Errors
System.err.println("Error in BufferedWriter, IOException");
} finally {
try {out.close();}
catch(Exception ex) {}
}

Declare your variable with a type of BufferedWriter. Writer does not have a newLine() method.
BufferedWriter out;
Methods are resolved, at compile time, based on the declared/static type of the variable (or expression) they are invoked on.
Alternatively, cast the variable
((BufferedWriter)out).write(outputFour);
but this is long.
Consider using try-with-resources.

Related

Java 8 file I/O NoSuchElementException: no line found

My goal is to read and write formatted strings to a file.
I'm actually using PrintWriter class for output and Scanner for input.
Code:
PrintWriter out = null;
Scanner in = null;
File file = new File(System.getProperty("user.dir")+"/data/level1/grounds.txt");
try {
out = new PrintWriter(file);
} catch (FileNotFoundException e) { e.printStackTrace(); }
out.println("foo");
try {
in = new Scanner(file);
} catch (FileNotFoundException e) { e.printStackTrace(); }
System.out.println(in.nextLine());
in.close();
The file is created, but in.nextLine() throws a NoSuchElementException: no line found.
After the execution (terminated by this exception) the file is blank.
Please leave a suggestion about how to do it correctly.
You should close the output printer once you are done with all writing to make it reflect in Scanner.
This is because out.println("foo"); writes in the PrintWriter but not on the file, you need to flush() to have the content on the file, you may close() also (this will automatically flush()
Simple flush
out.println("foo");
out.flush()
Close to flush
out.println("foo");
out.close()
Use an auto-flush PrintWriter
out = new PrintWriter(new FileOutputStream(file), true);

Java BufferedWriter - newLine() method

I have been encountering a problem for a while now, and have tested every possibility I can think of. Unfortunately, these possibilities did not work.
Basically, I am trying to write to a .txt file using BufferedWriter in Java. I need this setup so that I can have a line in between each piece of data. Imagine this is the text file produced from Java, it should look like this:
line1
line2
Here is my code:
public static void main(String[] args) {
Path path = Paths.get("test.txt");
if (!Files.exists(path)) {
try {
Files.createFile(path);
} catch (IOException e) {
System.out.println("Error in creating test.txt! Read the stacktrace
below.");
e.printStackTrace();
}
}
Charset charset = Charset.forName("UTF-8");
try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
String string = "line1";
writer.write(string, 0, string.length());
writer.newLine();
writer.newLine();
writer.flush();
} catch (IOException e) {
System.out.println("Unable to write to file! Read the StackTrace below.");
e.printStackTrace();
}
try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
String string = "line2";
writer.write(string, 0, string.length());
writer.flush();
} catch (IOException e) {
System.out.println("Unable to write to file! Read the StackTrace below.");
e.printStackTrace();
}
}
The output of this produces a text file as so:
line2
Now, I know I could just combine my two try/catches, and it would work. But this is just a test representation; in my real code, I need to do this separately so I can write in .txt files whenever specific events are triggered.
Basically, the newLine() methods are not saving unless I write text directly after them.
Any help is appreciated, as always!
The second BufferedWriter, or rather the second implicit FileWriter, overwrites the file created by the first one.
Combine the statements as you suggest, or use append mode (inefficient in this case).

Writing multiple lines to a new file in java?

When I open the newly written file in jGRASP, it contains many lines of text. When I open the same text file in notepad, it contains one line of text with the same data. The transFile is just a variable for the name of the text file that I am making.
FileWriter f = new FileWriter(transFile, true);
BufferedWriter out = new BufferedWriter(f);
out.write(someOutput + "\n");
out.close();
f.close();
I have changed the code to the following and it fixed the problem in notepad.
out.write(someOutput + "\r\n");
Why does this happen?
\r\n is the windows carriage return, which is what notepad will recognize. I'd suggest getting Notepad++ as it's just much much better.
The default line separator for windows (historically) is \r\n. The windows "notepad" app only recognizes that separator.
Java actually knows the default line separator for the system it's running on and makes it available via the system property line.separator. In your code you could do:
...
out.write(someOutput);
out.newLine();
...
the newLine() method appends the system's line separator as defined in that property.
You could do it this way also:
public void appendLineToFile(String filename, String someOutput) {
BufferedWriter bufferedWriter = null;
try {
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.append( someOutput );
bufferedWriter.newLine();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

not writing line by line

private static void displaytoFile(int trial, int count) {
// TODO Auto-generated method stub
String answer;
try{
// Create file
FileWriter fstream = new FileWriter(outputfile);
BufferedWriter out = new BufferedWriter(fstream);
answer = "Case #"+trial+": "+count;
out.write(answer);
out.newLine();
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
The displaytoFile() method is called in a loop in my project but i am not able to write line by line into the file.It only writes the last line ie the parameters passed during the last iteration.I tested in console and the other code is ok,it displays all but this code snippet seems to have some problem as it seems it overwrites the previous values.How can i get to write to file line by line?
Use the FileWriter(String, boolean) constructor in order to append the input instead of rewriting the entire file:
FileWriter fstream = new FileWriter(outputfile, true);
FileWriter fstream = new FileWriter(outputfile);
BufferedWriter out = new BufferedWriter(fstream);
answer = "Case #"+trial+": "+count;
out.write(answer);
out.newLine();
//Close the output stream
out.close();
has problem. This is because inside each iteration of your loop, you clear the file then write current line into it. you should open the file before the loop and close it after the loop. Or making sure that you are append to the file, not first clear then write, like what you did now.
You have to indicate that you want to append to the file
See method documentation here

How to add content to files using Java

I have a result being entered into a file. This result is being done on a loop. So, every time a new result comes, it has to be appended into a file, but it is being overwritten. What should I use in order to append my results into a single file?
Try
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
}
catch (IOException e) {
// handle exception
}
finally{
if(out != null){
try{
out.close();
}
catch(IOException e){
// handle exception
}
}
}
According to the API,
Constructs a FileWriter object given a
File object. If the second argument is
true, then bytes will be written to
the end of the file rather than the
beginning.
here is the basic snippet
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java 1");
out.write("Hello Java 2");
See Also
FileWritter - Javadoc
You should either keep the file open (sometimes it better, but usually not...) or open the output stream in append mode:
OutputStream os = new FileOutputStream(file, true);

Categories

Resources