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();
Related
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
I am currently writing a "text check" program in Java, but somehow I got stuck whilst creating an unique identifier for every file.
Actually I create an new identifier like this:
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
Also my program creates a new file and opens a BufferedWriter.
Actually when I now try to append (I tried using BufferedWriter#write, too, but it didn't work either.)
If I write this String into the file now, it looks like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4Nj
dGVzdC5zYzA
but it should be in only one line like this:
BlMjAxNi8wMy8zMSAyMDo0MjowOSMzMThhYjRkNS0yNjFhLTQwNjItODkyOS03NzlkZDIyOWY4NjdGVzdC5zYzA
At first I thought that it would probably have a problem with me creating a new line after using BufferedWriter#write, so I tried flushing my BufferedWriter before creating a new line. It didn't work either...
PS:
The whole neccessary code:
String name = file.getName().substring(0, ind);
File next = new File(folder.getAbsolutePath(), name+".sc0");
String identifier = Base64.encode((dateFormat.format(date) + "#" + uuid.toString() + "#" + name+".sc0").getBytes()).replace("=", "");
try {
next.delete();
next.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(next));
logger.info("Adding compiler identifier to file ...");
writer.write("#Script0:"+identifier);
writer.flush();
writer.newLine();
for(String str : lines) {
writer.newLine();
writer.append(str);
}
writer.flush();
writer.close();
} catch (IOException e) {
logger.error("Strange bug ... Did you delete the file? Please try again!");
return;
}
It's the encoder, not the BufferedWriter. Base-64 encoding uses a line length of (I believe) 72 characters.
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();
I'm appending to a text file but it won't go write to the next line, it keeps writing on the same line. I've tried .println() and PrintWriter.write("\r\n"); I'm not sure what else to do. (Windows System) Any help would be appreciated,
PrintWriter fOut;
try
{
fOut = new PrintWriter(new FileWriter("file_name.txt",true));
fOut.append("text\n");
fOut.close();
}
catch (IOException ex) {
Logger.getLogger(ScorePredictorFrame.class.getName()).log(Level.SEVERE, null, ex);
}
Assuming that file_name.txt already exists, and you want to write to the next line, I would do:
fOut.append("\r\ntext");
What is "text" in fOut.append("text\n");
if you are doing something like String text = ""; then you need to do it as fOut.append(text + "\n"); Else what you are doing is correct.
try
{
fOut = new PrintWriter(new FileWriter("file_name.txt",true));
fOut.println("text");
fOut.close();
}
The above code should work because according to the Java doc of the method it does enter the line separator
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
You can check the line.separator property using the following
final String lineSeparator = System.getProperty ( "line.separator" );
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