2014-01-28 82 views
0

我的问题是我们如何存储数据从网上使用java的PHP文件 (我可以查看PHP文件,但不能存储到我的数组变量)。这可能有利于他人。下面如何存储数据检索从Java文件的PHP文件

//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". 

是我当前的代码

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(); 

错误输出:

Exception in thread "main" java.lang.NullPointerException 

我已经参考了这个问题,但Retrieving info from a file混淆理解代码。 perhap任何好的人在这里可以提供有效的代码,如何将来自php文件的回声数据存储到我的java数组变量。

提前感谢民间。

ANSWER信贷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(); 

输出结果:

Ridzuan 
    Malaysia 

就像刚才那

回答

1

是的,你应该在inputLine得到这个例外。要知道我建议你调试你的代码。

作为解决方案,请尝试下面的代码。

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(); 
+0

感谢JJPA,它的工作原理,我感谢你的努力。我现在知道inputLine返回null并导致错误。我也把我的工作代码放在我的问题下,以便其他人可以受益。感谢其他也有帮助的人。 – Learner

0

使用花卉基地,而块。否则,您在while块之后使用nullinputLine。那是因为你在inputLine为空时离开循环。因此,当试图使用相同的,它扔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 
0

因为您的inputLine为NULL,您将得到NullPointerException。您正在运行循环,直到inputLine为NULL,然后在循环终止后,您正在使用该NULL变量来获取php结果。相反,根据您的需要将其存储在临时变量中,可以是String或数组。

例如,如果您需要将其存储在一个字符串,可以按如下

String inputLine, temp=""; 
while ((inputLine = in.readLine()) != null){ 
    temp.concat(inputLine); 
    System.out.println(inputLine); 
} 

然后使用变量temp访问结果做到这一点。

相关问题