How to store data retrieve from php file with java - java

my question is how do we store data from php file at web using java
(i can view the php file but cant store it into my array variable). may this benefit other.
//http://sampleonly.com.my/getInfo.php //this url is not exist. just for example
<?php
echo("Ridzuan");
echo("split");
echo("Malaysia");
echo("split");
?>
// i want to get the echo "Ridzuan" and "Malaysia". i dont want echo "split".
below is my current code
URL connectURL = new URL("http://sampleonly.com.my/getInfo.php");
BufferedReader in = new BufferedReader(
new InputStreamReader(connectURL.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
//array below should store input from .php file after i thrown "split" text
String[] strArray2 = inputLine.split(Pattern.quote("split"));
in.close();
error output:
Exception in thread "main" java.lang.NullPointerException
i have refer to this question, Retrieving info from a file but confuse to understand the code. perhap any good people here can provide me with valid code on how to store echo data from php file to my java array variable.
thanks in advance folk.
ANSWER credit to JJPA
URL connectURL = new URL("http://vmalloc.in/so.php");
BufferedReader in = new BufferedReader(
new InputStreamReader(connectURL.openStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
sb.append(inputLine);
}
String[] strArray2 = sb.toString().split(Pattern.quote("split"));
System.out.println(strArray2[0]);
System.out.println(strArray2[1]);
in.close();
output result:
Ridzuan
Malaysia
just like what i wanted

Yes you should get that exception in inputLine. To know I recommend you to debug your code.
As a solution try the below code.
URL connectURL = new URL("http://vmalloc.in/so.php");
BufferedReader in = new BufferedReader(new InputStreamReader(
connectURL.openStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
sb.append(inputLine);
}
// array below should store input from .php file after i thrown "split"
// text
String[] strArray2 = sb.toString().split("split");
System.out.println(strArray2);
in.close();

Use flower bases for while block. Otherwise you are using a null inputLine after the while block. That is because you are leaving the loop when inputLine is null. And hence, when tried to use the same, it threw a NullPointerException.
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
//array below should store input from .php file after i thrown "split" text
String[] strArray2 = inputLine.split(Pattern.quote("split"));
// do whatever you want with this array
} // while

You are getting NullPointerException because your inputLine is NULL. You are running the loop until the inputLine is NULL and then after the loop is terminated, you are using that NULL variable to get the php result. Instead, store it in a temporary variable, either String or array according to your need.
For example, if you need to store it in a string, you can do it as follows
String inputLine, temp="";
while ((inputLine = in.readLine()) != null){
temp.concat(inputLine);
System.out.println(inputLine);
}
And then use the variable temp to access the result.

Related

Parse JSON for first instance of repeated data field in Java with org.JSON

I'm trying to parse the first instance of "actualEPS" from the following JSON file:
{"symbol":"AAPL","earnings":[{"actualEPS":2.34,"consensusEPS":2.17,"estimatedEPS":2.17,"announceTime":"AMC","numberOfEstimates":10,"EPSSurpriseDollar":0.17,"EPSReportDate":"2018-07-31","fiscalPeriod":"Q3 2018","fiscalEndDate":"2018-06-30","yearAgo":1.67,"yearAgoChangePercent":0.40119760479041916,"estimatedChangePercent":0.29940119760479045,"symbolId":11},{"actualEPS":2.73,"consensusEPS":2.69,...}
Here is the method currently. I know I'm getting data from the target as I can Sysout the String "inputLine" and see the full file. I'm having trouble parsing from that point. I have installed and imported the org.JSON library.
public static void getData(String s) throws Exception {
String urlBase = new String(theWebSiteImGettingDataFrom)
URL targetURL = new URL(urlBase);
URLConnection yc = targetURL.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
} // end while
in.close();
JSONObject obj = new JSONObject(inputLine);
double eps = obj.getJSONObject("earnings").getDouble("actualEPS");
System.out.println("This is the first instance of EPS: " + eps);
} // end getData method
I'm getting a Null Pointer Exception in the stack trace:
at org.json.JSONTokener.<init>(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:357)
at code.URLConnectionReader.getData(URLConnectionReader.java:39)
How do I parse the data for the first instance of "actualEPS" and only the first instance?
EDIT
JSONObject obj = new JSONObject(inputLine);
JSONArray earningsArray = obj.getJSONArray("earnings");
JSONObject firstEPS = earningsArray.getJSONObject(0);
double eps = firstEPS.getDouble("actualEPS");
System.out.println("This is the first instance of EPS: " + eps);
First of all, as I have no idea how big your json is and as you only want to parse a specific part of the json itself, I would recommend you to use JsonReader.class instead of JsonObject.class.
Short difference:
JsonObject parses the whole json into RAM and needs to be smaller than 1 MB.
JsonReader uses a streaming approach, which allows you to handle big jsons more efficiently.
Secondly, if you know that you ALWAYS just need the first instance of your json you could simply shorten your jsonString itself before parsing it (e.g. substring, etc.).
Now to your code:
public static void getData(String s) throws Exception {
String urlBase = new String(theWebSiteImGettingDataFrom); // Semicolon!
URL targetURL = new URL(urlBase);
URLConnection yc = targetURL.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
} // end while
in.close();
System.out.println("My json: "+inputLine); //TODO: What is your output here?
JSONObject obj = new JSONObject(inputLine);
double eps = obj.getJSONObject("earnings").getDouble("actualEPS");
System.out.println("This is the first instance of EPS: " + eps);
} // end getData method
Please comment, as I can't tell if you get the json from your server.
EDIT:
Your error is in this line:
double eps = obj.getJSONObject("earnings").getDouble("actualEPS");
In short it should be like this:
double eps = obj.getJSONArray("earnings").getJSONObject(0).getDouble("actualEPS");
But, why? Your attribute earnings returns an JSONArray (Which means that you have multiple rows with indizes). So, instead of just requesting "earnings" as a JSONObject, you should rather use it as a JSONArray and then extract the first row (= .getJSONObject(0)). After extracting the first row you can actually use your double-Value.
I hope this works :)
2nd Edit:
Change that ..
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine); } // end while
to:
while ((inputLine += in.readLine()) != null) {
System.out.println(inputLine); } // end while
Your while loop keeps iterating until .readLine() returns null.
As null is the last iteration, you have only null in your variable.
As suggested you can solve that by simply changing the = to +=.
I hope we got it now. :)

How to read data from System.in to solve the task?

I'm working on this item. I did the spell checking algorithm but I have no idea how to read data correctly. When I use this:
StringBuilder text = new StringBuilder();
Scanner sc = new Scanner(System.in);
String temp;
while ((temp = sc.nextLine()).length() > 0){
text.append(temp);
}
/*spell checking algorithm*/
It waits for the empty string.
In this case:
while (sc.hasNext()){
text.append(temp);
}
it doesn't continue to execute the code at all. If I try to read 10000 signs I should type it all.
How could I read data correctly for this task?
Read them from file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
//do what you want
}

Getting this really annoying error when reading and putting a String into an array

This is my code to download and read the text in my file in Dropbox. Version is a URL.
BufferedReader in = new BufferedReader(new InputStreamReader(version.openStream()));
String inputLine;
int line = 0;
try{
while ((inputLine = in.readLine()) != null){
strings[line] = new String(inputLine);
line++;
}
} catch (Exception e){
e.printStackTrace();
}
Although, I get this really annoying error.
java.lang.ArrayIndexOutOfBoundsException: 1
at sky.the.venture.client.Download.getCredits(Download.java:38)
at sky.the.venture.client.LauncherFrame.credits(LauncherFrame.java:315)
at sky.the.venture.client.LauncherFrame.(LauncherFrame.java:49)
at sky.the.venture.Destiny.(Destiny.java:13)
at Start.main(Start.java:11)
So, the part which is an error is Download.java:38. Which is
strings[line] = new String(inputLine);
So if anyone can help, I will be really happy =D
Well presumably you only created an array like this:
String[] strings = new String[1];
Arrays don't resize themselves in Java - indeed, they can't be resized. If you want a dynamically sized collection, use a List<E> implementation e.g. ArrayList<E>:
List<String> lines = new ArrayList<String>();
while ((inputLine = in.readLine()) != null) {
lines.add(inputLine);
}
It appears that you are attempting to write to an element of the strings array that hasn't been allocated. For example, if you have allocated something like strings[10], and lines is incremented to 11, you will receive the ArrayIndexOutOfBoundsException exception.

Reading data from a URL and putting it into an ArrayList

Hi. I am trying to read a text file from a dropbox URL and put the contents of the text file to the ArrayList.
I was able to read and out print the data by using openStream() method but I can't seem to be able to figure out how to put that data into an ArrayList
URL pList = new URL("http://url");
BufferedReader in = new BufferedReader(
new InputStreamReader(
pList.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
would appreciate the help ?
List<String> list = new ArrayList<String>();
while ((inputLine = in.readLine()) != null) {
list.add(inputLine);
}
Try something like this:
String inputLine;
ArrayList<String> array = new ArrayList<String>();
while ((inputLine = in.readLine()) != null) {
array.add(inputLine);
}
It depends on what you want to do:
Store multiple DropBox files in an ArrayList, where 1 item represents 1 file
Use a StringBuilder to stitch all the lines together to one string.
List<String> files = new ArrayList<String>();
files.add(readFileUsingStringBuilder(pList));
public static String readFileUsingStringBuilder(URL url)
{
StringBuilder sb = new StringBuilder();
String separator = "";
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = br.readLine() != null)
{
sb.append(separator);
sb.append(line);
separator = "\n";
}
return sb.toString();
}
Store each line of the file in a record of the ArrayList
String inputLine;
ArrayList<String> array = new ArrayList<String>();
while ((inputLine = in.readLine()) != null) {
array.add(inputLine);
}

Alternative to .readLine() / readLine only returns lists

I'm using read line to get some text from wikipedia. But read line only returns lists, not the text that I want. Is there any way to use an alternative or to solve my problem?
public class mediawiki {
public static void main(String[] args) throws Exception {
URL yahoo = new URL(
"http://en.wikipedia.org/w/index.php?title=Jesus&action=raw"
);
BufferedReader in = new BufferedReader(
new InputStreamReader(yahoo.openStream())
);
String inputLine;
//http://en.wikipedia.org/w/index.php?title=Space&action=raw
while ((inputLine = in.readLine()) != null) {
String TEST = in.readLine();
//while ((inputLine = in.readLine()) != null)
//System.out.println(inputLine);
//This basicly reads each line, using
//the read line command to progress
WikiModel wikiModel = new WikiModel(
"http://www.mywiki.com/wiki/${image}",
"http://www.mywiki.com/wiki/${title}"
);
String plainStr = wikiModel.render(
new PlainTextConverter(),
TEST
);
System.out.print(plainStr);
}
}
}
The method readLine() on a BufferedReader instance definitely returns a String. In your code example, you are doing readLine() twice in your while loop. First you store it in inputLine:
while ((inputLine = in.readLine()) != null)
Then you are storing (the next line) in TEST without checking if it is null. Try to pass inputLine instead of TEST to the render method.

Categories