Writing to text files in Java - java

I have a method that writes a string to a text file using a DataOutputStream and the .writeBytes(String) method. If I write a string with a newline character, for example "I need \n help!", the new line is not displayed in notepad or other basic text editors. However, it does show up in WordPad, MS Word, etc. Why is this and can I fix it?

Mostly by using real text editors, which Notepad isn't.
You need to write system-specific newlines if you're not going to use a text editor that understands different flavors, or filter the file through something that does the conversion for you.
System.getProperty("line.separator");
This will give you an OS-specific line separator. It's less useful than you think.
System.out.printf("%n");
This does the same (and is available in String.format as well); also less useful than you think. It's more an editor thing, since any file could exist on any system, edited with any editor.

You should use System.getProperty("line.separator"); instead of directly using \n.

Related

Why Writting on txt file is different from console?

I want to save my ArrayList in a txt file, so i used PrintWriter. It is like a table, so I used the String.format method. When writing my data on the console, then it is perfect. But when writing on txt file it was different.
Why is it different when writing in txt file from console. Just see in below image?
It's probably because of tabs (\t) you are using. Apparently notepad has a different way of displaying tabs than the console. You might be able to use String.format to do some formatting, instead of adding tabs yourself, just check the JavaDoc for that.
See this question for a solution, for example:
String.format("%s, %s, %-20s%n", firstName, lastName, phoneNumber)
EDIT
Additional tip: you can add %n in the format string to get a platform specific newline (Added in above example).

Java adds spaces when reading in a line?

So I'm at my wit's end with this program. I'm reading in from a text file in Java. Barring everything that I do with the string once I have it, this is the bare minimum code to be shown.
while ((lineIn = myReader.readLine()) != null) {
System.out.println("LineIn: \""+lineIn+"\"");
System.out.println("Length: "+lineIn.length());
}
What it prints out, however, is very strange indeed. The line should read:
001 2014/06/09 09:40:24 0.000
But this is what I get:
LineIn: "�2�6�1�8� �2�0�1�4�/�0�7�/�1�0� �2�3�:�1�5�:�0�3� �0�.�0�0�0�"
Length: 61
On Stack Overflow it actually shows up fine. You may be able to copy and paste the "LineIn: etc" into your address bar and see there are little invisible spaces in the numbering. I have no idea why those are there, what they are, and where Java is getting them from. Opening the document it's sourced from in a simple text editor shows no such spacing, and copy+pasting from the text editor into the browser address bar has no superfluous spacing either. It's very peculiar and I hope someone can offer insight. I'm pulling out my hair here.
It looks like you're reading UTF-16 data as if it had an 8-bit encoding.
If you construct a java.io.InputStreamReader, you can specify the input text charset such as "UTF-16".
It could be due to the formatting and encoding that your reader is using, try using Scanner instead.
Java certainly is not doing that, it might be UTF-16 encoded file. Can you upload the file or a small part of it somewhere?

XML FILE LINE BREAKS

I am trying to use out writer in Java to create a XML file, but the generated XML File is in one line, which is very difficult to read and debug. I tried using backward-slash-n but the reader which I am using does not recognizes backward-slash-n so I need some alternative to break or backward-slash-n to add a line break to make it more readable and debug easily.
What should i do?
And also in notepad is there a way to add linebreaks using replace keyword for e.g., Search for > and replace with > + {Enter Key} i.e., line-break after every tag
In notepad++, you can search for
>
and replace with
>\r\n
just click the "Extended" search mode
Depending on how you do it, the text might be escaped twice. Try replacing \n with \\n.
As for the notepad part of the question I am very sure that it is not possible. I recommend Notepad++ (http://notepad-plus-plus.org). It supports this and many other functionalities, such as macros, converting between encodings, search/replace by regexp etc.

Passing Unicode line return characters set in Class to client side (DWR/HTML/UTF8) for InDesign Team

I've built a content management tool that allows a product team to create and manage product that gets exported to a website and for a different team of designers to create print ads for newspapers displaying the same product data.
My problem is with the InDesign graphic designers and the macros that they use within InDesign. The macros have the ability to take copy/pasted text/data and auto format the text inside InDesign based on the presence of certain characters. In particular the design team uses tab, "soft line break" (shift return), and regular line breaks (hard returns) in their macros.
Right now I generate a block of text with the records and the desired formatting characters in a java Class and then that's sent via DWR to the client side. When there is a requirement for a tab character I send \t, return is \r and I was hoping that a soft line break would be \n however InDesign seems to regard both \r and \n as a regular line break.
I had given up on being able to pass a soft-return until yesterday when I cam across Unicode \u2028 (soft line break) and \u2029 (regular line break). I've tried outputting both of these characters instead of \r and \n in the hopes that InDesign may regard these characters differently. In the box that the designers copy the output from it looks like there is no character there. There's no line break at all in the places where I've specific \u2028 to appear. When I copy/paste the output into a text editor it shows me that there is an unrecognized character there (it displays as a box with a question mark around it).
Platform is Java/MySQL running on Tomcat.
To date, I haven't had to deal too much with character encoding in this application. Header has <meta charset="utf-8" /> set but that's about it so far. I've tried setting this to utf-16 but it doesn't change the output. All of the tables in the MySQL database are set to utf8/utf8_general_ci.
Thoughts? How can I force InDesign to take copy/pasted text and recognize all of its macro capable characters? Actually, it's just the soft line breaks that it's not recognizing. HELP! :)
Thank you. Sorry this is so long!
Ryan V
I've been playing around with ID CS6 (OS X) for a while and I can't for the life of me get it to recognize a pasted LF as a forced line break. LF and CR and CRLF all go to paragraph breaks. U+2028 and U+2029 are display as empty glyphs, not breaks.
I'm a little wary of posting this as an answer, but I'll give it a go:
You might consider providing the text as a downloaded .txt file. CS5 introduced "Tagged Text" (a sort of XML-ish text document with full support for InDesign characters, attributes, etc.,) so this means your designers will be able to place the text file and InDesign will treat everything as intended.
To turn your existing text into CS5+'s Tagged Text (see the reference here), plop a <ASCII-MAC> or <ASCII-WIN> (as appropriate) as the first line and escape any '<' or '>'s with a backslash, then you're free to use <0x000A> as a forced line break. (literally those 8 characters)
That's probably mega-overkill, but it's certainly the most stupidly reliable way I can think of. I'll edit if I get anything else working.
NB. "forced line break" is the term InDesign itself uses for the character produced by Shift+Enter, your "soft line break;" contrast with "paragraph break" for a standard carriage return. InDesign apparently represents forced breaks with LF (U+000A) and paragraph breaks with CR (U+000D).
I'm not sure how you were trying to transfer and print out your characters (if you post your DWR and javascript code I might be able to help more), but one thing I would try is to ensure that your java output is actual UTF-8 using something like:
String yourRecordString = "Some line 1. \u2028Some line 2.";
ByteBuffer bb = Charset.forName("UTF-8").encode(yourRecordString);
Then, you can write out the bytes in bb into an output stream/file and check them. (Make sure to write them as bytes and not as a String nor as chars.) For example, the UTF-8 encoding of \u2028 is E2 80 A8, so you should see that sequence at the appropriate place in your output. (I use hexmode in vim for things like this.)
Then, make sure that these bytes get received back on the javascript side. (While I'm not an expert with DWR, I might prefer to make your java function return something other than a String.)
This should at least help you diagnose where the problem lies. If you do see that sequence and if InDesign still isn't recognizing the soft line breaks, then you at least know the problem is with InDesign and that you will have to find some other solution (such as modifying the designer's macros to recognize other characters).
(Also, note that you can see the default encoding for your JVM using Charset.defaultCharset(). My guess is that your default is not UTF-8 and that InDesign may have also had a problem with the UTF-16 you tried due to endianess or something like that.)

How to check which pattern use in file by java?

I am reading different files from different operating systems.
In file there are lots of lines. but i got info that after every line there may be use "\n" or "\r" or something like that.
When i read file by following instructions from Best way to read a text file [closed]
then what should i add to print in console by if-else conditions which explain in Class Pattern.
I need help please.
I am trying by reading this. But still need experts help.
Thanks.
If you're just printing to the console, you can simply use \n. To give you a little background, the times where those two separators really matter is within the files themselves (and when you must manually detect or write newlines in a file). In a unix-based system, newlines are represented in files by \n. In Windows, newlines are represented by \r\n. But when you are printing to the console, \n will perform correctly.
Also in the pattern matching example you gave. You're simply manually adding a newline so you can tell where a newline is. So especially in that case, you can mark the newline however you want as long as it's consistent.

Categories

Resources