Write a string in a file exactly how it is [duplicate] - java

This question already has answers here:
How to write new line character to a file in Java
(9 answers)
Closed 8 years ago.
How is possible to write a string in a file .txt exactly how it is?
For example, I want to write exactly the following string :
Hello, I'm an user of stackoverflow
and I'm asking a question
I tried with BufferedWriter, PrintWriter, PrintStream, but the result is always the same, so in my file .txt the string appears like this :
Hello, I'm an user of stackoverflow and I'm asking a question
It is necessary to analyze each character or is there an easier way?

The problem seems to be the line breaks.
If you use PrintWriter.println() the platform specific line separator is used: "\r\n" on Windows.
Windows Notepad will not handle "\n" but WordPad does.

Use any one
System.lineSeparator() to a new line after adding first message
PrintWriter#println() method to add a new line
Sample code: (Try any one)
try (BufferedWriter writer = new BufferedWriter(new FileWriter("abc.txt"))) {
writer.write("Hello, I'm an user of stackoverflow");
writer.newLine();
writer.write("and I'm asking a question");
}
try (PrintWriter writer = new PrintWriter(new FileWriter("abc.txt"))) {
writer.write("Hello, I'm an user of stackoverflow");
writer.println();
writer.write("and I'm asking a question");
}
try (FileWriter writer = new FileWriter("abc.txt")) {
writer.write("Hello, I'm an user of stackoverflow");
writer.write(System.lineSeparator());
writer.write("and I'm asking a question");
}
Read more about Java 7 The try-with-resources Statement to handle the resources carefully.

You can use the newLine() method of BufferedWriter class.
A newLine() method is provided, which uses the platform's own notion
of line separator as defined by the system property line.separator.
Not all platforms use the newline character ('\n') to terminate lines.
Calling this method to terminate each output line is therefore
preferred to writing a newline character directly.
You may try like this using \n as well:
String s ="Hello, I'm an user of stackoverflow\n"
+"and I'm asking a question";
or
String s = String.format("%s\n%s","Hello, I'm an user of stackoverflow",
"and I'm asking a question");

Related

RandomAccessFile setLength(0) adding a string of null characters to a file [duplicate]

This question already has answers here:
Clear contents of a file in Java using RandomAccessFile
(2 answers)
Closed 9 years ago.
I am trying to clear the contents of a file I made in java. The file is created by a PrintWriter call. I read here that one can use RandomAccessFile to do so, and read somewhere else that this is in fact better to use than calling a new PrintWriter and immediately closing it to overwrite the file with a blank one.
However, using the RandomAccessFile to clear the file seems to be adding a string of null characters to the file (or perhaps it is the PrintWriter?) It only occurs if more text is added.
PrintWriter writer = new PrintWriter("temp","UTF-8");
while (condition) {
writer.println("Example text");
if (clearCondition) {
writer.flush();
new RandomAccessFile("temp","rw").setLength(0);
// Although the solution in the link above did not include ',"rw"'
// My compiler would not accept without a second parameter
writer.println("Text to be written onto the first line of temp file");
}
}
writer.close();
Running the equivalent of the above code is giving my temp file the contents:
^#^#^#^#^#^#^#^#^#^#^#^#^#Text to be written onto the first line of temp file
The number of null characters is equal to the number of characters erased (including newline characters). If no new text is added to the file, it is completely blank.
NOTE: writer needs to be able to write "Example Text" to the file again after the file is cleared. The clearCondition does not mean that the while loop gets broken.
EDIT: I have no idea what caused those null characters. I realized I am stupid and there was no need to have a temp file, just a temp String with all the data that would later be written to a file. Strings are super easy to reset with = ""; Thanks for all the suggestions
It doesn't seem a good idea to have an opened PrintWriter on the file and use a RandomAccessFile at the same time.
If you close your writer and open a new one on the file (instead of using RandomAccessFile) I think it will suit your needs.

Inserting New Lines when Writing to a Text File in Java

I have a slight delema with learning FileWriter... The ultimate goal is writing a program that will "spawn" a .bat file that will be executed by the batch code that launched the .jar. The problem is, I have no clue how to make sure that every FileWriter.write(); will print on a new line... Any ideas??
To create new lines, simply append a newline character to the end of the string:
FileWriter writer = ...
writer.write("The line\n");
Also, the PrintWriter class provides methods which automatically append newline characters for you (edit: it will also automatically use the correct newline string for your OS):
PrintWriter writer = ...
writer.println("The line");
Use a BufferedWriter and use writer.newLine() after every write-operation that represents one line.
Or, use a PrintWriter and writer.println().
If you are using BufferedWriter then you can use an inbuilt method :
BufferedWriter writer = Files.newBufferedWriter(output, charset);
writer.newLine();

why the other part is not printed in the next line?

From the following code :
import java.io.*;
class fileTester {
public static void main( String args[]) throws IOException {
String string = "Suhail" + "\n" + "gupta";
FileOutputStream fos = new FileOutputStream( new File("break.txt"));
byte[] data = string.getBytes();
fos.write( data );
fos.close();
}
}
I expected the output to be :
Suhail
Gupta
int the file created (i.e both the strings in a new line ) but the output is in a single line. Suhail gupta
Why is it so when i have used \n character in between the 2 Strings ?
You shouldn't hard-code the new line character when writing to a file. Use the OS-specific newline String instead:
String newline = System.getProperty("line.separator");
Also, rather than use a FileOutputStream to write raw bytes to a text file, why not wrap it in a PrintStream object so you can easily just use println(...) to do your newlines for you?
I guess you are using notepad to see the file.
End of line character varies from system to system. A more advanced text editor (v.g. Notepad++) will show it correctly, because it tries to find the system that this file was prepared for.
Usually, instead of using always "\n", use
java.lang.System.getProperties().get("line.separator")
If your operating system is windows than you have to use \r\n for a new line, only \n won't work in windows, you can find more details here
This is because for Windows new line is: \r\n. In other OS \n will be good
when you need a new line, the best practice is to use the system newline string, by putting in System.getProperty("line.separator") where you want a line break.
That way, it will use the right new line for the platform you are making the file on (windows/mac/linux).

How to append to the end of a file in java?

...
Scanner scan = new Scanner(System.in);
System.out.println("Input : ");
String t = scan.next();
FileWriter kirjutamine = new FileWriter("...");
BufferedWriter out = new BufferedWriter(writing);
out.write(t)
out.close();
...
if I write sometring into the file, then it goes to the first line. But if run the programm again, it writes the new text over the previous text (into the first line). I want to do: if I insert something, then it goes to the next line. For example:
after 1 input) text1
after 2 input) text1
text2
and so on...
what should i change in the code?
thanks!
java.io.PrintWriter pw = new PrintWriter(new FileWriter(fail, true));
This should do it. Use that over the existing pw line.
edit: And as explained in the comments, this is causing the following things to happen:
A FileWriter is being created, with the optional 'append' flag being set to true. This causes FileWriter to not overwrite the file, but open it for append and move the pointer to the end of the file.
PrintWriter is using this FileWriter (as opposed to creating its own with the file you pass it.)
(A lot of editing going on here. I was uncertain about the question a few times.)
I suggest you use the append flag in the FileWriter constructor.
You also might line to add a newline between each write ;)
why dont you use RandomAccessFile?
In RandomAccessFile, read/write operations can be performed at any position.The file pointer can be moved to anyplace by seek() method. You have to specify file opening mode while using it.
Example:
RandomAccessFile raf = new RandomAccessFile("anyfile.txt","rw"); // r for read and rw for read and write.
and to take the file pointer to EOF you have to use seek().
raf.seek(raf.length());
Instead of using BufferedWriter, use
PrintWriter out = new PrintWriter(kirjutamine);
out.print(t);
out.close();

Newlines in string not writing out to file

I'm trying to write a program that manipulates unicode strings read in from a file. I thought of two approaches - one where I read the whole file containing newlines in, perform a couple regex substitutions, and write it back out to another file; the other where I read in the file line by line and match individual lines and substitute on them and write them out. I haven't been able to test the first approach because the newlines in the string are not written as newlines to the file. Here is some example code to illustrate:
String output = "Hello\nthere!";
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("test.txt"), "UTF-16"));
System.out.println(output);
oFile.write(output);
oFile.close();
The print statement outputs
Hello
there!
but the file contents are
Hellothere!
Why aren't my newlines being written to file?
You should try using
System.getProperty("line.separator")
Here is an untested example
String output = String.format("Hello%sthere!",System.getProperty("line.separator"));
BufferedWriter oFile = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("test.txt"), "UTF-16"));
System.out.println(output);
oFile.write(output);
oFile.close();
I haven't been able to test the first
approach because the newlines in the
string are not written as newlines to
the file
Are you sure about that? Could you post some code that shows that specific fact?
Use System.getProperty("line.separator") to get the platform specific newline.
Consider using PrintWriters to get the println method known from e.g. System.out

Categories