Format a String in Json style - java

I extracted a huge String from a webpage and want to style/formatting this in Json style. The extracted String was originally a Json format but now after extracting this is just a long String. I used JsonObj for this and the formatter does curios things, he moved text from the bottom to top changed the generally the line orders etc.
http://pastebin.com/exwwc6SY JsonFile after Formatting
http://pastebin.com/WHXtE36G The extracted String
And here the code
try {
FileWriter fw = new FileWriter("/tmp/1.txt");
String line = ROUtils.getStringFromInputStream(urlConnection.getInputStream());
System.out.println(line);
String jsonObj = new JSONObject(line).toString(2);
fw.write(jsonObj);
} catch (IOException e) {
e.printStackTrace();
}
And the getStringFromInputStream() method
public static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return sb.toString();
}
Update
I found a new issue. The JsonObj File its not equal to the original String.
I compared the number of Characters (no spaces). The original String has 96311 and the JsonObj has 92636. Can anyone give me a hint what should I do?

You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at http://www.json.org/
An object is an unordered set of name/value pairs.

I found it out why i missed 4000 characters after converting.
I forgot to close the FileWriter!
fw.close();
The close() methods calls the flush() method so that the last buffered piece of the String can written down.
Thank u guys.

Related

Get last element of an array

through an API I get an array with a lot of different data. But I only need the last element.
The variable sb has the array in it. But i cannot access elements like that: sb[0] (for example)
If I print the variable sb it looks like that:
{"data":[[[1583596801195,279.52],[1583596814340,279.52],[1583596815535,279.44563849372383],[1583596816730,279.2060000000001],[1583596913525,279.2060000000001],[1583596914720,279.28824435146447],[1583596915915,279.52],[1583597211080,279.52],[1583597212275,279.52000000000004],[1583597213470,279.52],[1583597609015,279.52],[1583597610210,279.5199999999999],[1583597707005,279.5199999999999],[1583597708200,279.52000000000004],[1583597709395,279.52],[1583597806190,279.52],[1583597807385,279.52000000000004],[1583597993805,279.52000000000004]]]}
In this case, I only need the last element (279.52000000000004).
My code look like that:
URL url = new URL("the URL i get the data from");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
InputStream instream = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(sb);
Sorry I am not experienced that experienced with programming. But I would really appreciate if someone could help me.
Thank you for your help.
If you need the last element only, you should not be appending the results.
Instead, replace the previous value stored.
String result = null;
String line = null;
try {
while ((line = reader.readLine()) != null) {
//sb.append(line + "\n");
result = line; // not appending, but replacing
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(result);
You can try this, replace this line "System.out.println(sb) with below code :
String s = new String(sb);
String d[] = s.split(",");
System.out.println(d[d.length -1].replaceAll("]", ""));
This would print the exact data you want i.e 279.52000000000004

formatting while writing a document

I am reading a txt file into a String buffer and writing the content into a word document using OutputStreamWriter.
The problem is that the formatting is not retained in the document. The spaces and the line breaks are not retained as in the text file. The txt file is formatted properly with spaces, page breaks, and tabs. I want to replicate the txt in word document. Please suggest how can the same formatting be retained. The link to the file is: http://s000.tinyupload.com/index.php?file_id=09876662859146558533.
This is the sample code:
private static String readTextFile() {
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
sb.append(System.lineSeparator());
}
content = sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
private static void createDocument(String docName, String content) {
FileOutputStream fout = null;
try {
fout = new FileOutputStream(docName);
OutputStreamWriter out = new OutputStreamWriter(fout);
out.write(content);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Try to change your readTextFile() like this and try.
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while(line != null) {
content += line + "\n";
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
Actually if your using java 7, you can use try-with-resources in order to decrease the number of lines in your code.
Try to avoid printing \n chars. Use \r\n for Windows - remember that line separators differ across platforms.
A more reliable way is to use PrintWriter, see
How to write new line in Java FileOutputStream
After the discussion in comments:
the source file has unix line breaks
the output file is expected to have Windows line breaks
we shall strip the 0x0c (form feed - i.e. move to next page on the printer) from the source file, as it is non-printable.
public static void main(String[] args) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("f:\\order_invoice.txt")))
.replace("\u000c","");
PrintWriter printWriter=new PrintWriter(new FileWriter("f:\\new_order_invoice.txt"));
for (String line:content.split("\\n")) {
printWriter.println(line);
}
printWriter.close();
}
So:
read the file as it is into a String
get rid of the form feed (0x0c, unicode u000c)
split the string at unix line breaks \n
write it out line by line using PrintWriter which uses the platform default line ending, i.e. windows cr-lf.
Remember that you can actually do this in one line, using a regexp to replace unix line endings to windows line endings in the string representing the whole file, and use Files.write to write out the whole file in one line. However this presented solution is probably a bit better as it always uses platform native line separators.

When to use String and when char array in Java?

I am supposed to read a large file containing a string in each line. What is the best way to parse this kind of file in Java?
Currently I am parsing like this using BufferedReader:
public static List<String> readFile(String filename) {
List<String> input = new ArrayList<>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(filename));
while ((sCurrentLine = br.readLine()) != null) {
input.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return input;
}
So my question here is, which one is a better way: to save like an array of String or an array of char arrays?
In other words, is it better to have too many String objects or too many char arrays?
EDIT:
I need to check if the string in each line is a palindrome or not.
In above scenario, you can use either of these. If you want change the content further, then you have to use array of char because String is immutable in nature in java.

Reading from a text file in java is returning some garbage value

I'm performing certain commands through command prompt and storing the values in a text file.
wmic logicaldisk where drivetype=3 get deviceid > drive.txt
Now I want to read the string stored in the text file from my java file. When I try to do this:
try {
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i=0;
while ((string[i] = in.readLine()) != null) {
System.out.println(string[i]);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
I get the output as follows:
ÿþD[]E[]V[]I[]C[]E[]
how to avoid this?
while ((string[i] = in.readLine()) != null) {
System.out.println(string[2]);
}
over there you are missing the i++;
However I would advise you to use this structure: Use a ArrayList instead of an array, since this allows you to have a self-resizing structure, also instead in the while use the method ready(); from the BufferedRead in order to check the end from the document, at the end the for it's just to display the elements in String ArrayList.
ArrayList<String> string = new ArrayList<String>();
try {
File file = new File("drive.txt");
BufferedReader entrada;
entrada = new BufferedReader(new FileReader(file));
entrada.readLine();
while (entrada.ready()) {
string.add(entrada.readLine());
}
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String elements : string) {
System.out.println(elements);
}
Why do you need a string array here? The size of the array may be wrong? Simply use a string instead of array. I tried this and works fine for me:
try {
String string;
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i = 0;
while ((string = in.readLine()) != null) {
System.out.println(string);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
If you are using eclipse IDE, change the encoding type. Go to Edit->Set Encoding-> Others->UTF-8.

How to get the content of an input stream in reverse order?

I am using a txt file for my level desing. I use the below to take the contents and convert to string buffer, then iterate through the lines to generate my game objects.
The the problem is that it reads from top down and so I have to design my levels upside down for them to be right way around.
How can I change the stream to read the opposite way? Or write the lines to the String Builder the opposite way?
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
Log.w("LOG", e.getMessage());
} finally {
try {
is.close();
} catch (IOException e) {
Log.w("LOG", e.getMessage());
}
}
return sb.toString();
You could just use sb.insert(0, line + "\n") instead of sb.append(line + "\n");.
This will always add new lines to the front of the string, not append it to the end. Should do exactly what you want and will be just as fast, because StringBuilder is made exactly for things like that.

Categories