I have a Java app that writes to a file with:
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile));
bw.write(line + lineTermination);
Line termination is defined as:
\r\n
I get the odd, mysterious blank line inserted into my file.
I get no extra lines if I change my code to:
bw.write(line);
bw.newLine();
But I want to force a specific line ending, not use System property. Clients specifically request a line ending character - some even have |. Its not a viable fix to just use \n.
Here is an snippet of the data with missing line:
"KABE","14/01/11","14:35","14:56","1987","US","SS","CO","MARRIED WITH CHILDREN","","EINE SCHRECKLICH NETTE FAMILIE","","N","10","","12","O'NEILL ED","13","SAGAL KATEY"
"PRO7","14/01/11","14:35","14:55","2001","US","SS","CO","SCRUBS","","SCRUBS DIE ANFAENGER","","C","10","BERNSTEIN ADAM","12","BRAFF ZACH","13","CHALKE SARAH"
Thanks for your time :-)
You can call
System.setProperty("line.separator", "\r\n");
in order to set the system property inside your code.
Related
I have a java application that takes input via a Scanner reading System.in, and gives output via System.out. The scanner is always active, it does not terminate without using Ctrl+C via the terminal or ending the process in an IDE.
I'm running into some behavior that leads me to believe System.out is not flushing properly.
In my code there are the lines:
System.out.print(",\\" + '\n');
System.out.print(" " + someString);
(someString does not contain a newline character)
When I execute this code via the terminal, the whitespace and someString are not printed to the terminal. However in my IDE's console, it is. (IntelliJ)
If I change the second statement to println instead of print, it works fine, but it does append a new line between one execution of the code and the next, which is not workable here. (Maybe there's something I can do with a carriage return?)
This sounds a lot like the output isn't being flushed, as its only System.out.print that has the trouble. However, adding System.out.flush() after the print statement does not cause it to print.
This sounds a lot like the output isn't being flushed, as its only System.out.print that has the trouble.
Typically System.out and System.err are configured differently. (System.err is typically not buffered, and System.out is typically buffered.) However, the javadocs do not specify the flushing behavior of either streams. This could explain the differences in behavior between the (real) console and running in an IDE.
For info, here is how the streams are initialized in Java 8:
FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
setIn0(new BufferedInputStream(fdIn));
setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));
private static PrintStream ewPrintStream(FileOutputStream fos, String enc) {
if (enc != null) {
try {
return new PrintStream(new BufferedOutputStream(fos, 128),
true, enc);
} catch (UnsupportedEncodingException uee) {}
}
return new PrintStream(new BufferedOutputStream(fos, 128), true);
}
As you can see, System.out is initialized as buffered with autoflush enabled.
However, adding System.out.flush() after the print statement does not cause it to print.
Are you sure about that? A flush() should flush any buffered output.
I suggest that the problem is actually somewhere else; e.g. the print or flush calls are not happening ... for some reason.
It is also possible that some of your problems are due to this:
System.out.print(",\\" + '\n');
As #javaguy points out, a newline character is a platform specific line separator. On some platforms, the console requires something different. The simplest platform independent way to tell the console to do a line break is:
System.out.println(",\\");
Or putting it all together:
System.out.println(",\\");
System.out.print(" " + someString);
System.out.flush(); // This is necessary ... and should work.
Assuming that you are running the program in Windows, the carriage
return (\r) and line feed (\n) together need to be added to print
the new line as below:
System.out.print(",\\" + '\r\n');
System.out.print(" " + someString);
System.out.println() places the cursor to the next line after execution. so you don't need to add "\n". That's probably why a line of space is between the lines.
Just do this:
System.out.println(",\\");
System.out.println(" " + someString);
I have a.txt list trying to move the first line to the last line in Java
I've found scripts to do the following
Find "text" from input file and output to a temp file. (I could set
"text" to a string buffRead.readLine ??) and then...
delete the orig file and rename the new file to the orig?
Please for give me I am new to Java but I have done a lot of research and can't find a solution for what I thought would be a simple script.
Because this is Java and concerns file IO, this is a non-trivial setup. The algorithm itself is simple, but the symbols required to do so are not immediately evident.
BufferedReader reader = new BufferedReader(new FileReader("fileName"));
This gives you an easy way to read the contents of the file fileName.
PrintWriter writer = new PrintWriter(new FileWriter("fileName"));
This gives you a simple way to write to the file. The API to do so is the exact same as System.out when you use a PrintWriter, thus my choice to use one here.
At this point its a simple matter of reading the file and echoing it back in the correct order.
String text = reader.readLine();
This saves the first line of the file to text.
while (reader.ready()) {
writer.println(reader.readLine());
}
While reader has text remaining in it, print the lines into the writer.
writer.println(text);
Print the line that you saved at the start.
Note that if your program does anything else (and it's just a good habit anyway), you want to close your IO streams to avoid leaking resources.
reader.close();
writer.close();
Alternatively, you could also wrap the entire thing in a try-with-resources to perform the same cleanup automatically.
Scanner fileScanner = new Scanner(myFile);
fileScanner.nextLine();
This will return the first line of text from the file and discard it because you don't store it anywhere.
To overwrite your existing file:
FileWriter fileStream = new FileWriter("my/path/for/file.txt");
BufferedWriter out = new BufferedWriter(fileStream);
while(fileScanner.hasNextLine()) {
String next = fileScanner.nextLine();
if(next.equals("\n") out.newLine();
else out.write(next);
out.newLine();
}
out.close();
Note that you will have to be catching and handling some IOExceptions this way. Also, the if()... else()... statement is necessary in the while() loop to keep any line breaks present in your text file.
Add the same line to the last line of this file have a look into this link https://stackoverflow.com/a/37674446/6160431
I want to write a few arguments in a .txt file and I want to sort them. To do that I want to go to the next line for every groop of arguments but I dont know how to do that.I have tried the:
x.nextLine();
statement, but that is only for scanning and not for formatting.
How can I go to the next line of a file while formatting? Is there another statement for that?
This is the code I created:
try{
w = new Formatter("data.txt");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Fatal Error, please Reboot or reinstal program", "Error", JOptionPane.PLAIN_MESSAGE);
}
w.format("%s,%s,%s,%s%n", book,code,author,editor);
w.close();
You write
w.format("%s,%s,%s,%s%n", book,code,author,editor);
and I assume you want a newline where you write %n. But newline is \n, so change your code to
w.format("%s,%s,%s,%s\n", book,code,author,editor);
Also, you may want to revise the error catching logic in the program: right now if opening the file fails, you show an error message, which is good, but after that your program continues execution and will crash and burn on the first write operation...
EDIT: every time you execute the line w.format("%s,%s,%s,%s\n", book,code,author,editor); a line terminated by a new line will be added to the file, as long as you don't close the file or restart the program, because the Javadoc for the constructor you use says:
fileName - The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
So, if you need a file that grows instead of being overwritten you should use one of the other available constructors, eg one accepting an Appendable as argument. This would lead to the following code:
FileWriter fstream = new FileWriter("data.txt",true);
Formatter w = new Formatter(fstream);
// do whatever your program needs to do
w.close();
Of course surrounded by the necessary exception handling.
Given:
try{
FileWriter fw = new FileWriter(someFileName);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Hello Java");
}catch...
}finally{
bw.close();
}
It works perfectly in windows, but not in Unix.
Remark: the created file in unix has the complete 777 rights!
What should I do to get it working in unix?
Thanks,
Roxana
Try doing a
bw.flush();
before closing the file (on try block).
Maybe the information is still on the buffer, so it doesn't get reflected on the file contents
You should give us some more code, specially the section where the someFileName is specified. Since there is some difference in Java on how the 'file separator' is treated, your problem could be that you're creating/opening a file in windows, but it isn't on the unix... and your 'catch' is treating it, but you didn't provide its contents.
Take a look here
"file.separator" --> Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.
I aim to make an index of all files with a particular extension and store it into index.txt. I am getting all the right results but not getting the 'files' onto the new line, this is a snapshot of my code:
OutputStream f0 = new FileOutputStream("index.txt");
String ind[] = f.list(only); // logic for getting only relevant files
for(int i=0;i<ind.length;i++)
{
File n = new File(path + "/" +ind[i]);
System.out.println(ind[i]+ " is a " +exten +" file");
ind[i]+="\n"; // doesnt work
f0.write(ind[i].getBytes()); // here i am writing the filenames
}
is it due to the getBytes() function which overlooks the "/n" ? Please tell me what to do. I want to insert a new line everytime i exit the for loop.
One major edit: I am getting the desired result when I open the file with notepad++ or wordpad, but when i open the file with notepad i am getting the results on the same line. Please Explain this too!
Try writing:
System.getProperty("line.separator")
instead of \n
Instead of using an FileOutputStream I'd use a PrintWriter.
PrintWriter out = new PrintWriter("index.txt");
String ind[] = f.list(only); // logic for getting only relevant files
for(int i=0;i<ind.length;i++)
{
File n = new File(path + "/" +ind[i]);
System.out.println(ind[i]+ " is a " +exten +" file");
out.println(ind[i]);
}
Is there any reason you are working at such a low level of I/O in Java? First of all you should be using Writers instead of OutputStreams.
And then if you use PrintWriter you can do away with the getBytes piece:
PrintWriter f0 = new PrintWriter(new FileWriter("index.txt"));
And then later...
f0.print(ind[i]);
And finally to your question, outside the loop simply
f0.println();
There is a missing assumption here.
If you assume that your text file should have MS Windows line separators (meant for Windows platforms), then you should use \r\n.
If you assume that your text file should have Unix-like line separators (meant for GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), then you should use \n.
If you assume that your text file should have Mac oldschool line separators (meant for Mac OS up to version 9, Apple II family, OS-9, etc.), then you should use \r.
If you assume that your text file should have line separators of the kind of the platform your program is run from, then you should use System.getProperty("line.separator") (or print the new line with a .println()).
try this,
FileWriter.write("\r\n");