I'm using a buffered writer to write words in a text file, which works. But the writer starts at a new line every time, so you get all the words underneath each other with output.nextLine(); Can I check if a line is empty with an if statement so it wont print an empty line?
Here's the code:
BufferedWriter output = new BufferedWriter(new FileWriter("products.txt", true));
output.newLine();
output.append(s+" : "+price+" Euro");
output.close();
Because right now my txt file has an empty line at the top if I dont have text there.
To write to a file line by line without printing empty lines, change your code to the following:
BufferedWriter output = new BufferedWriter(new FileWriter("products.txt", true));
output.append(s+" : "+price+" Euro\n");
output.close();
Related
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.
I have coded the following FileWriter:
try {
FileWriter writer = new FileWriter(new File("file.txt"), false);
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
writer.write(sizeX);
writer.write(sizeY);
writer.flush();
writer.close();
} catch (IOException ex) {}
Now I want to insert a new line, just like you would do it with \n normally, but it doesn't seem to work.
What can be done to solve this?
Thank you.
If you want to get new line characters used in current OS like \r\n for Windows, you can get them by
System.getProperty("line.separator");
since Java7 System.lineSeparator()
or as mentioned by Stewart generate them via String.format("%n");
You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically
PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
// ^^^^^^^ will add OS line separator after data
(BTW System.out is also instance of PrintStream).
Try System.getProperty( "line.separator" )
writer.write(System.getProperty( "line.separator" ));
Try wrapping your FileWriter in a BufferedWriter:
BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();
Javadocs for BufferedWriter here.
Since 1.8, I thought this might be an additional solution worth adding to the responses:
Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException
StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());
If appending to the same file, perhaps use an Append flag with Files.write()
Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);
Try:
String.format("%n");
See this question for more details.
If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write(jTextField1.getText());
writer.write(jTextField2.getText());
writer.newLine();
writer.flush();
writer.close();
} catch (IOException ex) {
System.out.println("File could not be created");
}
Here "\n" is also working fine. But the problem here lies in the text editor(probably notepad). Try to see the output with Wordpad.
One can use PrintWriter to wrap the FileWriter, as it has many additional useful methods.
try(PrintWriter pw = new PrintWriter(new FileWriter(new File("file.txt"), false))){
pw.println();//new line
pw.print("text");//print without new line
pw.println(10);//print with new line
pw.printf("%2.f", 0.567);//print double to 2 decimal places (without new line)
}
I would tackle the problem like this:
BufferedWriter output;
output = new BufferedWriter(new FileWriter("file.txt", true));
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
output.append(sizeX);
output.append(sizeY);
output.newLine();
output.close();
The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?
using simple \n to break line in write file and normal output in java
In Java I want to write a String to end of a specific line in file. The simple way:
BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
bw.write(String);
does not work because it always writes at the end of file. Is there a simple way?
You have to get the line number where you want to add the string.... Then iterate over the the file with readLine().
while (br.readLine() != null) {
if (actualLine == yourLine) // write the String
actualLine ++;
}
I have coded the following FileWriter:
try {
FileWriter writer = new FileWriter(new File("file.txt"), false);
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
writer.write(sizeX);
writer.write(sizeY);
writer.flush();
writer.close();
} catch (IOException ex) {}
Now I want to insert a new line, just like you would do it with \n normally, but it doesn't seem to work.
What can be done to solve this?
Thank you.
If you want to get new line characters used in current OS like \r\n for Windows, you can get them by
System.getProperty("line.separator");
since Java7 System.lineSeparator()
or as mentioned by Stewart generate them via String.format("%n");
You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically
PrintStream fileStream = new PrintStream(new File("file.txt"));
fileStream.println("your data");
// ^^^^^^^ will add OS line separator after data
(BTW System.out is also instance of PrintStream).
Try System.getProperty( "line.separator" )
writer.write(System.getProperty( "line.separator" ));
Try wrapping your FileWriter in a BufferedWriter:
BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();
Javadocs for BufferedWriter here.
Since 1.8, I thought this might be an additional solution worth adding to the responses:
Path java.nio.file.Files.write(Path path, Iterable lines, OpenOption... options) throws IOException
StringBuilder sb = new StringBuilder();
sb.append(jTextField1.getText());
sb.append(jTextField2.getText());
sb.append(System.lineSeparator());
Files.write(Paths.get("file.txt"), sb.toString().getBytes());
If appending to the same file, perhaps use an Append flag with Files.write()
Files.write(Paths.get("file.txt"), sb.toString().getBytes(), StandardOpenOption.APPEND);
Try:
String.format("%n");
See this question for more details.
If you mean use the same code but add a new line so that when you add something to the file it will be on a new line. You can simply use BufferedWriter's newLine().
Here I have Improved you code also: NumberFormatException was unnecessary as nothing was being cast to a number data type, saving variables to use once also was.
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write(jTextField1.getText());
writer.write(jTextField2.getText());
writer.newLine();
writer.flush();
writer.close();
} catch (IOException ex) {
System.out.println("File could not be created");
}
Here "\n" is also working fine. But the problem here lies in the text editor(probably notepad). Try to see the output with Wordpad.
One can use PrintWriter to wrap the FileWriter, as it has many additional useful methods.
try(PrintWriter pw = new PrintWriter(new FileWriter(new File("file.txt"), false))){
pw.println();//new line
pw.print("text");//print without new line
pw.println(10);//print with new line
pw.printf("%2.f", 0.567);//print double to 2 decimal places (without new line)
}
I would tackle the problem like this:
BufferedWriter output;
output = new BufferedWriter(new FileWriter("file.txt", true));
String sizeX = jTextField1.getText();
String sizeY = jTextField2.getText();
output.append(sizeX);
output.append(sizeY);
output.newLine();
output.close();
The true in the FileWriter constructor allows to append.
The method newLine() is provided by BufferedWriter
Could be ok as solution?
using simple \n to break line in write file and normal output in java
Following snippet attempts to write the name of directories and files present in some directory to a text file.Each name should be written to a separate line.Instead it prints each name on the same line. Why is it so ?
try {
File listFile = new File("E:" + System.getProperty("file.separator") + "Shiv Kumar Sharma Torrent"+ System.getProperty("file.separator") +"list.txt");
FileWriter writer = new FileWriter(listFile,true);
Iterator iterator = directoryList.iterator();
while(iterator.hasNext()) {
writer.write((String)iterator.next());
writer.write("\n"); // Did this so each name is on a new line
}
writer.close();
}catch(Exception exc) {
exc.printStackTrace();
}
output:
Where am i making a mistake ?
Whenver you need textual formatting always use PrintWriter.
The right way of doing is to wrap the writer inside a PrintWriter and use println() method, like:
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println();
If you are using Windows, use \r\n instead of \n.
or for OS-independent, use:
System.getProperty("line.separator");
You should write your next line as "\r\n" if you are on a Windows platform.
The next line for Windows is "\r\n"
The next line for Mac is "\n"
Alternatively, use System.getProperty("line.separator") for your line break. It automatically determines the right line break for the system it is running on. This should be the best practice since Java is expected to perform the same on different OS-es.
If you are going to use BufferedWriter :
File f = new File("C:/file.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write("Hello");
bw.newLine(); // new line
bw.write("How are you?");
bw.close();