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
Related
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.
Good evening, I'm sorry for my english. I want to try to deduce, using a link from json in the console. Sometimes is used json-simple-1.1.1.jar. I do not understand what the problem is, writes
Exception in thread "main" java.lang.NullPointerException at
kkkkkkkkkkkk.main.main (main.java:34)
private static final String filePath = "http://ksupulse.tk/get_all.php";
public static void main(String[] args) throws org.json.simple.parser.ParseException {
try {
URL serverAddress = new URL(filePath);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.connect();
int rc = connection.getResponseCode();
if(rc == 200) {
String line = null;
BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null)
sb.append(line + '\n');
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString());
//error
JSONArray array = (JSONArray) obj.get("response"); //<-------err this line
for(int i = 0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("id")+": "+list.get("name"));
}
} else {
System.out.println("Connect error");
}
connection.disconnect();
} catch (java.net.MalformedURLException e) {
e.printStackTrace();
} catch (java.net.ProtocolException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
Can u provide the json text ?This is happening due to improper parsing of json text. The error is "Null Pointer Exception" . These types of error occur when you try to access some undefined resource . A good way to debug this one is to use a general exception and try to find the exact error . Your code is only handling 3 errors .You need to handle other errors also. Try using this.
try{
//Some code
}(Exception e){
System.out.println("Error:"+e.toString());
}
I am using a StringBuilder as shown below. When there is some value everything is ok. But sometimes no values are appended, so i am expecting empty as result. But when I check the value of result in the eclipse adt latest version , i see a strange string value like [Ljava.lang.StackTraceElement;#405a3c98 having length 39.
Any ideas? Is this normal? Should I put a if condition to avoid this situation, that is , if length is 0 than return empty string ?
StringBuilder builder = new StringBuilder("");
...
...
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream));
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
String result = builder.toString();
Just after 2 hours , i saw the code below :(). Thanks guys:)
catch (ClientProtocolException e) {
e.printStackTrace();
return e.getStackTrace().toString();
} catch (IOException e) {
e.printStackTrace();
return e.getStackTrace().toString();
}
return builder.toString();
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.
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.