Appending to JTextArea is not creating a line break on '\n' - java

I'm loading string resources from a text file (so as to not have to rebuild if I need to change them) which when appended to the JTextArea displays as "Some sentence,\n on the same line."
When I hard code the exact same String, it appends fine.
Where could this be going wrong?

What does your text file look like? If "\n" is in the text file it's probably copied literally, i.e. it's not treated as an escape sequence.
EDIT: You could try reading the text file as a property file and automatically have e.g. \n parsed a newline.
Properties p = new Properties();
InputStream fileStream = new FileInputStream("myfile.txt");
p.load(fileStream);
String value = p.getProperty(key);

In the text file do this...
"1st_Half_of_String"+"\n"+"2nd_Half_of_String"

Related

Reading path from ini file, backslash escape character disappearing?

I'm reading in an absolute pathname from an ini file and storing the pathname as a String value in my program. However, when I do this, the value that gets stored somehow seems to be losing the backslash so that the path just comes out one big jumbled mess? For example, the ini file would have key, value of:
key=C:\folder\folder2\filename.extension
and the value that gets stored is coming out as C:folderfolder2filename.extension.
Would anyone know how to escape the keys before it gets read in?
Let's also assume that changing the values of the ini file is not an alternative because it's not a file that I create.
Try setting the escape property to false in Ini4j.
http://ini4j.sourceforge.net/apidocs/org/ini4j/Config.html#setEscape%28boolean%29
You can try:
Config.getGlobal().setEscape(false);
If you read the file and then translate the \ to a / before processing, that would work. So the library you are using has a method Ini#load(InputStream) that takes the INI file contents, call it like this:
byte[] data = Files.readAllBytes(Paths.get("directory", "file.ini");
String contents = new String(data).replaceAll("\\\\", "/");
InputStream stream = new ByteArrayInputStream(contents.getBytes());
ini.load(stream);
The processor must be doing the interpretation of the back-slashes, so this will give it data with forward-slashes instead. Or, you could escape the back-slashes before processing, like this:
String contents = new String(data).replaceAll("\\\\", "\\\\\\\\");

character serialization,BufferedReader in Java

if I have a delimited text file with apostrophes in, like ' as in:
BB;Art’s Tavern;6487 Western Ave., Glen Arbor, MI 49636;
what do I need to do to allow those to be parsed correctly through a BufferedReader in Java?
the code Im currently using to open the file for reading is thus in an android application:
StringBuffer buf = new StringBuffer();
InputStream is = context.getResources().openRawResource(R.raw.lvpa);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
Currently the apostrophes are being returned as question marks ? in a black box.
The contents of the file are then parsed into a model.
any help would be appreciated:)
Thanks
The file you are reading is not recorded in UTF-8. You need to know which encoding your file is in before you attempt to read it. If possible open it in whatever text editor you use to examine it and save it off in UTF-8 and try reading it again. (Some text editors will give the option of setting the encoding when you save the file.)

How to write Burmese text into CSV file android

I want to write Burmese text into .csv file. After writing Burmese text to a .csv file I open that file with MS Office but it does not show the Burmese text.
A Burmese font is setup in my PC.
Below is my code:
OutputStreamWriter char_output = new OutputStreamWriter(new
FileOutputStream(CSV.getAbsolutePath().toString()),
Charset.forName("UTF-8").newEncoder());
char_output.write(message + str);
char_output.write("\n");
for (int i = 0; i < pList.size(); i++)
{
StringBuilder sb = new StringBuilder();
sb.append(pList.get(i).getOrderNumber()).append(",").append(pList.get(i).getProductName()).append(",");
sb.append(pList.get(i).getProductDiscription()).append(",").append(pList.get(i).getWeightKg()).append(",");
sb.append(pList.get(i).getWeightViss()).append(",").append(pList.get(i).getQty()).append(",");
sb.append(pList.get(i).getDate()).append("\n");
char_output.write(sb.toString())`FileOutputStream(CSV.getAbsolutePath().toString() ),
}
char_output.close();
Many would say, use a CSV library.
Instead of Charset.forName("UTF-8").newEncoder() it suffices to use "UTF-8", but not wrong.
Instead of "\n" under Windows "\r\n" might be more convenient. (System.getProperty("file.encoding") would take Android's "\n".)
You need to handle commas and quotes. If a string value contains a comma, then it should be withing double quotes. Every inner double quote self-escaped, that is doubled.
Instead of a comma, also semi-colon is used. Even better is a tab character "\t".
To detect UTF-8, you may write a BOM character at the begin of file. This is a zero-width space. BOM = Byte Order Mark, refering to UTF-16LE and UTF-16BE (reversed byte pair).
sb.append("\uFEFF"); // Add a BOM at the begin of file.
The file ending might be ".csv" but you may also lie, and give it an ending ".xls" to let Excel open it by double clicking.

How to place an XML file in form of a String inside Java file

I am using Eclipse IDE
I have a big XML file .
I wan to copy this XML file and provide it in form of a String .
String XMLStringSource = "XML Content Here" ;
I am getting errros with double quotes in the XML file , please tell me how can we resolve this ??
You should not do that. In fact, it is impossible beyond a certain size as there is a limit of 64KB on the bytecode of methods (which include initializers).
The correct way to do it is put the XML file next to the source code and use Class.getResourceAsStream() to read the file.
You can configure Eclipse to escape text when pasting into a string literal.
Go to Window > Preferences > Java > Editor > Typing.
Select the checkbox which says "Escape text when pasting into a string literal".
Press Apply.
Now create a String literal e.g.
String xml = "";
Copy your xml and paste it inside the quotes. Eclipse will automatically escape it for you.
This is quite handy for small bits of xml or text.
If you have a large file, then you should read the file into a string instead.
Yow will need to escape the quotes. But this will change the look of XML; it will be a combination of Java String/XML. Also if the the XML file is big like you say then you will need to do a search and replace for quotes " with escaped quotes \" before pasting into the java file.
try
{
FileReader fstream = new FileReader("D:\\File.xml");
BufferedReader out = new BufferedReader(fstream);
String y="";
while ((y=out.readLine()) != null) {
System.out.println(y);
}
//out.close();
}catch(Exception e) {
e.printStackTrace();
}
is this acceptable? just read the file line by line, the String variable will have double quotations and they wont generate an error. If reading step by step can solve problem.

Java: how to write formatted output to plain text file

I am developing a small java application. At some point i am writing some data in a plain text file. Using the following code:
Writer Candidateoutput = null;
File Candidatefile = new File("Candidates.txt"),
Candidateoutput = new BufferedWriter(new FileWriter(Candidatefile));
Candidateoutput.write("\n Write this text on next line");
Candidateoutput.write("\t This is indented text");
Candidateoutput.close();
Now every thing goes fine, the file is created with the expected text. The only problem is that the text was not formatted all the text was on single line. But if I copy and paste the text in MS Word then the text is formatted automatically.
Is there any way to preserver text formatting in Plain text file as well?
Note: By text formatting I am referring to \n and \t only
Use System.getProperty("line.separator") for new lines - this is the platform-independent way of getting the new-line separator. (on windows it is \r\n, on linux it's \n)
Also, if this is going to be run on non-windows machines, avoid using \t - use X (four) spaces instead.
You can use line.separator system property to solve your issue.
E.g.
String separator = System.getProperty("line.separator");
Writer Candidateoutput = null;
File Candidatefile = new File("Candidates.txt"),
Candidateoutput = new BufferedWriter(new FileWriter(Candidatefile));
Candidateoutput.write(separator + " Write this text on next line");
Candidateoutput.write("\t This is indented text");
Candidateoutput.close();
line.separator system property is a platform independent way of getting a newline from your environment.
A PrintWriter does this platform independent - use the println() methods.
You would have to use the Java utility Formatter which can be found here: java.util.Formatter
Then all you would have to do is create an object of Formatter type such as this:
private Formatter output;
In this case, output will be the output file you are writing to.
Then you have to pass the file name to the output object like this:
output = new Formatter("name.of.your.file.txt")
Once that's done, you can either hard-code the file contents to your output file using the output.format command which is similar to the System.out.println or printf commands.
Or use the Scanner utility to input the data into memory then use output.format to output this data to the output object or file.
This is an example on how to write a record to output:
output.format( "%d %s %s %2f\n" , field1.decimal, field2.string, field3.string, field4.double)
There is a little bit more to it than this, but this sure beats parsing data, or using a bunch of complicated third party plugins.
To read this file you would redirect the Scanner utility to read a file instead of the console:
input = new Scanner(new File( "name.of.your.file.txt")
Window's Notepad needs \r\n to display a new-line correctly. Only \n is ignored by Notepad.
Well Windows expects a newline and a carriage return char to indicate a new line. So you'd want to do \r\n to make it work.

Categories

Resources