我在Java新m.How解決以下error.On result.append(行)它拋出空指針異常。 下面是代碼空指針異常錯誤當附加字符串值
public class test {
private static StringBuffer result = null;
public static void main(String[] args) {
printCSV();
}
private static void generateCsvFile(String sFileName,StringBuffer result)
{
try
{
FileWriter writer = new FileWriter(sFileName);
writer.append(result.toString());
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void printCSV() {
try {
URL url = new URL(protocol + "://" + hostname + "/apiv2/csv.xml?username=" + userName + "&password="
+ password + "&form_id=" + formId + "&begin_second=962461752&end_second=1593613752");
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
System.out.println(urlCon);
urlCon.connect(); // Connecting
BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
result.append(line);
}
generateCsvFile("d:\\test.csv",result);
System.out.println(result);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
我認爲你的「結果」對象仍然是空的,你是在哪裏實例化的? – hallie
他沒有實例化它。如果他實例化它,它應該永遠不會拋出一個空指針異常,當它使用append()函數 –