Replace \n in BufferedWriter.write()? - java

I have a String that contains for example "Name: Foo \n Date: 12/13/11 \n"
When I do BufferedWriter.write(String) to a text file it actually outputs the \n is there anyway to do a replace on \n to something that when written to a text file will signify a line break?
Here is sample code.
String input = "Name: adfasd \n AN: asdfasdf \n";
Writer textOutput = null;
File file = new File("write.txt");
textOutput = new BufferedWriter(new FileWriter(file));
textOutput.write( input );
textOutput.close();
The output would be
http://img7.imageshack.us/img7/7694/exampleve.png

Windows uses CR+LF line endings as opposed to LF endings. You should be able to use \r\n to get your desired result.
Wikipedia has an article about newlines if you want to know more.

If the string contains the text \n as opposed to the character \n, then you can do
String text = "Line 1 \\n Line2";
System.out.println(text);
System.out.println(text.replace("\\n", "\n"));

This is strange, I just tested the following code, and the resulting file displays the message on two lines :
public void test() throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("/someDir/test.txt"));
writer.write("Hello\nWorld");
writer.close();
}
Result :
Hello
World

Related

Remove a line in text file with java.BufferedReader

How can I remove or trim a line in a text file in Java?
This is my program but it does not work.
I want to remove a line in text file, a line contain the word of user input
try {
File inputFile = new File("temp.txt");
File tempFile = new File("temp1.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = name;
String currentLine;
while((currentLine = reader.readLine()) != null)
{
//trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(!trimmedLine.startsWith(lineToRemove))
{
// if current line not start with lineToRemove then write to file
writer.write(currentLine);
}
}
writer.close();
reader.close();
}
catch(IOException ex)
{
System.out.println("Error reading to file '" + fileName + "'");
}
You are not separating the lines with a line break character, so the resulting file will have one single long line. One possible way to fix that is just writing the line separator after each line.
Another possible problem is that you are only checking if the current line starts with the given string. If you want to check if the line contains the string you should use the contains method.
A third problem is that you are not writing the trimmed line, but the line as it is. You really don't say what you expect from the program, but if you are supposed to output trimmed lines it should look like this:
if(!trimmedLine.contains(lineToRemove)) {
writer.write(trimmedLine);
writer.newLine();
}
startsWith() is the culprit. You are checking if the line starts with "lineToRemove". As #Joni suggested use contains.

Writing to A Text File-Writing To Next Line

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" );

Java : replaceAll and .split newline doesn't work

I am wanting to split a line up (inputLine) which is
Country: United Kingdom
City: London
so I'm using this code:
public void ReadURL() {
try {
URL url = new URL("http://api.hostip.info/get_html.php?ip=");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
String line = inputLine.replaceAll("\n", " ");
System.out.println(line);
}
in.close();
} catch ( Exception e ) {
System.err.println( e.getMessage() );
}
}
when you run the method the the output is still
Country: United Kingdom
City: London
not like it's ment to be:
Country: United Kingdom City: London
now i've tried using
\n,\\n,\r,\r\n
and
System.getProperty("line.separator")
but none of them work and using replace, split and replaceAll but nothing works.
so how do I remove the newlines to make one line of a String?
more detail: I am wanting it so I have two separate strings
String Country = "Country: United Kingdom";
and
String City = "City: London";
that would be great
You should instead of using System.out.println(line); use System.out.print(line);.
The new line is caused by the println() method which terminates the current line by writing the line separator string.
http://docs.oracle.com/javase/1.5.0/docs/api/java/io/BufferedReader.html#readLine()
Read that. readLine method will not return any carriage returns or new lines in the text and will break input by newline. So your loop does take in your entire blob of text but it reads it line by line.
You are also getting extra newlines from calling println. It will print your line as read in, add a new line, then print your blank line + newline and then your end line + newline giving you exactly the same output as your input (minus a few spaces).
You should use print instead of println.
I would advise taking a look at Guava Splitter.MapSplitter
In your case:
// input = "Country: United Kingdom\nCity: London"
final Map<String, String> split = Splitter.on('\n')
.omitEmptyStrings().trimResults().withKeyValueSeparator(": ").split(input);
// ... (use split.get("Country") or split.get("City")

Replace every quotation in a file by an escaping quotation with java

I am trying to edit a file with java.
I would like to escape every Quotation " in my file with \"
I tried it like this (regards to the other solution on stackoverflow, which code I could copy):
public void replaceInFile(File file) throws IOException {
File tempFile = new File("twittergeoUpdate.csv");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while (br.ready()) {
fw.write(br.readLine().replaceAll("\"", "\\\"") + "\n");
}
fw.close();
br.close();
fr.close();
}
I was too fast... It doesn't work for me. The Quotation just stay untouched in my file. Any ideas ?
\\\" only escapes "(double quote), you have to escape the back-slashes aswell, thus you need 5 backslashes. \\\\\"
s.replaceAll("\"", "\\\\\"")
You should use StringEscapeUtils#escapeJava() from Apache commons-lang package.
Like this:
org.apache.commons.lang.StringEscapeUtils.escapeJava(<yourStringLiteralHere>)
From javadoc:
StringEscapeUtils#escapeJava() escapes the characters in a String using Java String rules.
Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
So a tab becomes the characters '\' and 't'.
The only difference between Java strings and JavaScript strings is that in JavaScript, a single quote must be escaped.
Example:
input string: He didn't say, "Stop!"
output string: He didn't say, \"Stop!\"
I coded:
public void replaceInFile(File file) throws IOException {
File tempFile = new File("twittergeoUpdate.csv");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while (br.ready()) {
fw.write(br.readLine().replaceAll("\"", "\\\\\"") + "\n");
}
fw.close();
br.close();
fr.close();
}//replaceInFile
The correct replacement string is \\\" (5 backslash, not 3)
The basic problem is that you cannot write to a file you are reading from and not expect it to change. In your case, the first thing FileWriter does is truncate the file. I have seen examples where the reader still manages to read something but it is corrupted.
You have to write to a temporary file, close both files and when finished replace (using delete and rename) your original file with the temporary one.

Write Java String to file with special encoding

I have got the Java String ôð¤ Ø$î1<¨ V¸dPžÐ ÀH#ˆàÀༀ#~€4` which I would like to write to a file with ANSI encoding.
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output),"windows-1252"));
try {
out.append(str);
} finally {
out.close();
}
Debugger says that str contains ôð¤ Ø$î1<¨ V¸dPÐ ÀH#àÀà¼#~4. As soon as I write it to the output file, the file only contains ?ÒÜ#4. So whats wrong with my method writing to the File?
Sorry for this weird strings - I am trying to rewrite a delphi 7 function in java. These strings are the only samples I have got.
If I run
String text = "ôð¤ Ø$î1<¨ V¸dPžÐ ÀH#ˆàÀༀ#`~€4";
Writer writer = new OutputStreamWriter(new FileOutputStream("test.txt"), "windows-1252");
writer.append(text);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"), "windows-1252"));
String line = br.readLine();
br.close();
System.out.println(line.length() + ": '" + line + "' matches " + line.equals(text));
it prints
32: 'ôð¤ Ø$î1<¨ V¸dPžÐ ÀH#ˆàÀༀ#`~€4' matches true
so no characters are lost in translation.
If I change the encoding to "US-ASCII" I get the following output
32: '??? ?$?1<? V?dP?? ?H#??????#`~?4' matches false

Categories