Java appending to text file working differently on another system? - java

When I run the below on a windows machine it works as expected, appending to the end of the text file on a new line, however when run in a jail on my FREENAS server inputs will simply append to the last line and never make a new line. Has anyone experienced this?
BufferedWriter writer = new BufferedWriter(new FileWriter(filename,true));
writer.newLine();
writer.append(desired);
writer.close();

Despite the textfile looking like this after being given input on Windows:
cat
dog
mouse
and on FREENAS the textfile looking like this:
catdogmouse
They are both treated the same by Java and when read in with:
String line = Scanner.nextLine();
System.out.println(line);
Both produce:
cat
dog
mouse

Related

Replace string in text file using Java

I have a text file (file.txt) which contains multiple lines:
/location/test/file.csv
/location/test1/file2.csv
/location/test2/file.exe
Using ECMA, I would like to replace all instance of "/" with "\". However, the code below only replaces the first line and eliminate lines 2 and 3.
This is the result of the file.txt file after I run the code (as I said, lines 2 and 3 are missing):
\location\test\file.csv
Can anyone please help?
function ReadFile ()
{
var file = new java.io.BufferedReader(new java.io.FileReader("C:\\Test\\file.txt"));
var fileWriter = new java.io.FileWriter("C:\\Test\\file.txt",false);
while ((line = file.readLine()) != null)
{
println(line);
if (line.contains ("/"))
line = line.replace("/","\\");
fileWriter.write(line);
fileWriter.close();
}
}
ReadFile ();
So I managed to run this code using Rhino. It does in fact run. I made some changes to filenames in order to get it running on my mac, but it is essentially the same code:
function ReadFile () {
var file = new java.io.BufferedReader(new java.io.FileReader("file"));
var fileWriter = new java.io.FileWriter("file2",false);
while ((line = file.readLine()) != null) {
if (line.contains ("/"))
line = line.replace("/","\\");
fileWriter.write(line + "\n");
}
fileWriter.close();
file.close();
}
ReadFile ();
So the bugs you had were:
Reading and writing to the same file. This is awkward using streams. Basically, don't do it. I changed it to write to file2.
Closing the writer inside your reader loop. Close the writer at the end, once closed, you can no longer write to it.
Not closing the file you are reading from.
For those interested in how I got this running, on OS X, using rhino:
brew install rhino
rhino example.js
I had to remove the println because that wasn't recognised but that wasn't a critical part. JS on the JVM. Fun! Except nothing is async.....
There are other JS engines too, but rhino worked.
JavaScript String object has a replace method that takes a regular expression that can replace characters in a String. However, the Java in your JavaScript won't work because you are mixing up two languages.
http://www.w3schools.com/jsref/jsref_replace.asp
The problem is that you're writing over the file as you're reading it, so as soon as your first write(line) completes, the file no longer has the next two lines. Either use a second, temporary file to write to until you've finished processing the file, or keep a list/array of all the new lines in memory, and then write out the file at the end.
I'm really curious to know, though, how you managed to get your current program to even run. In my experience, Java and ECMA/Javascript are two completely separate languages, but it looks like you're using javascript code against Java libraries. What's up with that?

Format of the output

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

Java File Handling writing in File not 'overwriting'

i am doing basic File Handling in Java. what i want is that once i run my code and .txt file is created in specified location and some Text is writtern there , now next time when i write something it should not OVERWRITE it , but should start ahead of it .. For example first time i wrote "Hello java" , next time when i run program and try to write "Java is good " file should have something like this "Hello java " "java is good",,
Right now i am doing this
BufferedWriter bf = new BufferedWriter( new FileWriter("c:\\test.txt"));
bf.write("Hello Java");
bf.close();// and so on .
now when next time i run and type
BufferedWriter bf = new BufferedWriter( new FileWriter("c:\\test.txt"));
bf.write("Java is good ");
bf.close();// and so on .
it should not overwrite , So pleas guide mt about it . Thanks in advance
Just add a boolean argument with value 'true' to the FileWriter constructor.
FileWriter#FileWriter(File, boolean)

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

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