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
Related
My code reads through an xml file encoded with UTF-8 until a specfied string has been found. It finds the specified string fine, but I wish to write at this point in the file.
I would much prefer to do this through a stream as only small tasks need to be done.
I cannot find a way to do this. Any alternative methods are welcome.
Code so far:
final String RESOURCE = "/path/to/file.xml";
BufferedReader in = new BufferedReader(new InputStreamReader(ClassLoader.class.getResourceAsStream(RESOURCE), "UTF-8"));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ClassLoader.class.getResource(RESOURCE).getPath()),"UTF-8"));
String fileLine = in.readLine();
while (!fileLine.contains("some string")) {
fileLine = in.readLine();
}
// File writing code here
You can't really write into the middle of the file, except for overwriting existing bytes (using something like RandomAccessFile). that would only work, however, if what you needed to write was exactly the same byte length as what you were replacing, which i highly doubt.
instead, you need to re-write the file to a new file, copying the input to the output, replacing the parts you need to replace in the process. there are a variety of ways you could do this. i would recommend using a StAX event reader and writer as the StAX api is fairly user friendly (compared to SAX) as well as fast and memory efficient.
I am using eclipse to run my program. My programs gives 1000 lines as output, and I write the output on a text file successfully. The problem is that the output on the text file is not same as on the console. On the console there are separate lines, but on text file all lines are appended as one line.
How to get the same console format in a text file?
You will have to make sure of the following:
When writing a line to a file you are including a line separator character(s), you can get a platform independent line separator using the following
System.getProperty("line.separator");
When viewing the text file, some app's (like notepad) may not display new line characters the same as others
The app you are using to view the file will need to be set to view in a monospaced font (such as Courier New)
completely guessing what you are doing but i think you need to do this.
BufferedWriter bw = new BufferedWriter(new FileWriter(f, false));
while ( rs.next() ) {
// code to write a line.
bw.write("\r\n");
}
use
bw.write("\r\n");
instead of
bw.newLine();
This is for windows systems POSIX systems do newlines differently i believe.
\n is a new line operator just remember that.
Well if you are using a PrintWriter I would simply do
PrintWriter pw = new PrintWriter(file);
while(...you still have data){
pw.println(<yourString>);
}
you can also append the string "\n" to create a new line manually
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();
I need a way to delete a line, im using this to write on the file:
FileWriter insert = new FileWriter(file, true);
PrintWriter out = new PrintWriter(insert);
out.println("1. Mario");
I made a thing that reads line by line but i've no idea how to delete the string that returns, is that even possible?
While you're reading in the lines of text write then lines you want to keep to a StringBuffer or StringBuilder then write the contents of the buffer/builder back to the file. Is there any specific reason that you're opening up the file for appending when you're wanting to remove lines of text from the file or am I missing something?
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).