Line separator for Windows in java - java

I would like to save some words into *.txt file. But there is one condition: each word must be on new line. So I wrote this:
String content ="";
String nl = System.lineSeparator();
content += "my" + nl + "some" + nl + "random" + nl + "words";
But this code not working - all words are in the same line.
So i tried with special characters - \r\n :
String content ="";
content += "my" + "\r\n" + "some" + "\r\n" + "random" + "\r\n" + "words";
Still didn't works - in file all words are in same line:
mysomerandomwords
In addition to this: my string content is save to file by:
<button class="button">Download</button>
What kind of separator should I use to put words in another lines?
(I'm using Netbeans 8.0. File is opens in windows notepad).

Use base64 in data URI scheme:
<button class="button">Download</button>
In your Java code do:
String content ="";
String nl = System.getProperty("line.separator");
content += "my" + nl + "some" + nl + "random" + nl + "words";
content = DatatypeConverter.printBase64Binary(content.getBytes("utf-8"));
Demo: http://jsfiddle.net/bDRAq

Try with System.getProperty("line.separator")
Read it here about System Properties with complete list of System properties.
The System class maintains a Properties object that describes the configuration of the current working environment.
"line.separator" - Sequence used by operating system to separate lines in text files
What System.lineSeparator() states?
Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator.
On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".
Why use System.getProperty()?
"line.separator" property can be changed by passing arguments as shown below
java -Dline.separator=
Have a look at Should I cache System.getProperty(“line.separator”)?

Well, it depends how you write down the content. If you write it to a file on the filesystem, it will most likely end up correctly. But you are not saving it to a file with your program, but you let the browser do that by including a link in a html file. When including characters in HTML, you need to encode them with the URLEncoder class.
Since it looks to me that you are working within an WebContainer, since you JSP structures, you could also implement a Servlet that returns the requested data.

Related

How can i make that everything after "," in .txt file will be checked separetly :)?

I need to improve this code that will read from a text file named file.txt
sergy,many,mani,kserder
I would like to use this form :
file = login.getText();
if (file.equals("sergy"))
I just need to do something that will read everything in the text file separately and ignoring "," sign, or something else other than "," sign.
You could split the string by the , character and check if any of the array's elements are equal to the value you're looking for:
file = login.getText();
if (Arrays.asList(file.split(",")).contains("sergy")) {
// do something...

Replace empty string with Non-Disclosed

I am a novice in Java so please pardon my inexperience. I have a column (source) like below which has empty strings and I am trying to replace it with Non-Disclosed.
Source
Website
Drive-by
Realtor
Social Media
Billboard
Word of Mouth
Visitor
I tried:
String replacedString = Source.replace("", "Non-Disclosed");
After running the above snippet, everything gets replaced by Non-Disclosed:
Non-Disclosed
Non-Disclosed
Non-Disclosed
............
How can I tackle this issue? Any assistance would be appreciated.
I think you simply have to do : Source.replace("\n\n", "\nNon-Disclosed\n")
I am assuming that your entire column is stored in one string.
In that case you can use ^$ regex to represent empty line (with MULTILINE flag (?m) which will allow ^ and $ to represent start and end of lines).
This approach
will work for many line separators \r \n \r\n
will not consume those line separators so we don't need to add them back in replacement part.
To use regex while replacing we can use replaceAll(regex, replacement) method
DEMO:
String text = "Source\r\n" +
"\r\n" +
"\r\n" +
"\r\n" +
"Website\r\n" +
"Drive-by\r\n" +
"Realtor\r\n" +
"Social Media\r\n" +
"\r\n" +
"Billboard\r\n" +
"\r\n" +
"Word of Mouth\r\n" +
"\r\n" +
"Visitor";
text = text.replaceAll("(?m)^$", "Non-Disclosed");
System.out.println(text);
Output:
Source
Non-Disclosed
Non-Disclosed
Non-Disclosed
Website
Drive-by
Realtor
Social Media
Non-Disclosed
Billboard
Non-Disclosed
Word of Mouth
Non-Disclosed
Visitor
You can use
String replacedString = Source.trim().isEmpty() ? "Non-Disclosed" : Source;
to replace only the "blank" String.

Fixing malformed XML with java

I have several files containing the following XML element:
<table cellpadding="0" cellspacing="0" border="0"style="width:100%">
The part that says border="0"style=" needs a space between the 0 value and style attribute.
Unfortunately there are too many files with this issue to make manually going and inserting the space a viable option.
I can edit attributes and I can edit values by creating an Xpath that gets the table as a NodeList, creates a node and gets the attributes.. but how would I add a space between the attribute and the value??
We could always just String.split("\""); aka split on the commas.
Here, try this:
/** In reality, you would probably read file to string?
* or read line by line? either way is an easy fix!
*/
String input = ("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\"style=\"width:100%\">");
String xmlTag = StringUtils.substringBetween(input, "<", ">");
Starting with index number, array after split contains as follows:
XML Tag Name
ODD INDICES ~ 1, 3, 5, and so on, contain: attribute name.
EVEN INDICES ~ 2, 4, 6, and so on, contain: attribute value.
int arrSize = xmlCharValPairs.length()
String[] xmlCharValPairs = xmlTag.split("\"");
StringBuilder sb = new StringBuilder(arrSize);
sb.append("<" + xmlCharValPairs[0] + " ");
for (int i = 1; i < arrSize-1; i++) {
if (i%2 == 0)
sb.append("\"" + xmlCharValPairs[i].trim() + "\" ");
else
sb.append(xmlCharValPairs[i]);
}
String returnXMLFormat = sb.toString();
This will leave you with an XML String in your requested format :)
If it's consistent length then all you need to write is a simple string parser that would add extra "" at X position.
If it's not the same everything I think I would try to check if char is " then a char -1 from it and then check if it's =" or (some letter)" for example a".
width="100" vs width="100" anotherparam="...
This could tell you if it's begining or end of param. If it's the ending then simply add a space char after it.
Obiously you could then check if it's "(someletter) or "(space) to know if there is space char after your apostrophe.
width="100" param2="..." vs width="100"param2=""
If you have lets say 200 files to edit you could use something similar to this:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
Then simply open files in a loop, edit them and save them to new files with their orginal names or just overwrite current files. It's up to you.
Your file isn't well-formed XML so you will need a tool that can handle files that aren't well-formed XML. That rules anything in the XSLT/XQuery/XPath family.
You can probably fix nearly all occurrences of the problem, with low risk of adverse side effects, by using a regular expression that inserts a space after any occurrence of " that isn't immediately preceded by =. (This will add some unnecessary spaces, but the XML parser will ignore them.)

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.

java read write unicode / UTF-8 filenames (not contents)

i have a few directories/files with Japanese characters. If i try to read a filename (not the contents) containing (as example) a ク i receive a String containing a �. If i try to create a file/directory containing an ク a file/directory appears containing a ?.
As example:
I list the files with.
File file = new File(".");
String[] filesAndDirs = file.list();
the filesAndDirs array now contains the directories this the special characters. The String now only contains ����. It seams there is nothing to decode because the a getbytes shows only "-17 -65 -67" for every char in the filename even for different chars.
I use MacOS 10.8.2 Java 7_10 and Netbeans.
Any ideas?
Thank You in advance :)
Those bytes are 0xef 0xbf 0xbd, which is the UTF-8-encoded form of the \ufffd character you're seeing instead of the Japanese characters. It appears whatever OS function Java is using to list the files is in fact returning those incorrect characters.
Perhaps Files.newDirectoryStream will be more reliable. Try this instead:
try (DirectoryStream<Path> dir = Files.newDirectoryStream(Paths.get("."))) {
for (Path child : dir) {
String filename = child.getFileName().toString();
System.out.println("name=" + filename);
for (char c : filename.toCharArray()) {
System.out.printf("%04x ", (int) c);
}
System.out.println();
}
}
It's a bug in the old java File api (maybe just on a mac). Anyway, it's all fixed in the new java.nio.
I have several files containing unicode characters in the filename and content that failed to load using java.io.File and related classes. After converting all my code to use java.nio.Path EVERYTHING started working. And I replaced org.apache.commons.io.FileUtils (which has the same problem) with java.nio.Files...
...and be sure to read and write the content of file using an appropriate charset, for example: Files.readAllLines(myPath, StandardCharsets.UTF_8)

Categories

Resources