我执行代码时出错

时间:2014-12-23 06:31:28

标签: java

我是Java的初学者,我想从文本文件中读取和写入一个字符串,我尝试了我的想法,但它不起作用。它告诉我一个错误...... 请参阅下面的代码:

import java.util.*;
import java.io.*;

public class Uptime {


    public static void main(String[] args) {

        FileWriter fileWriter = null;
        try
        {
            double Oldtime=0;
            BufferedReader read=new BufferedReader(new FileReader("C:/eGurkha/agent/sample/UptimeRecord.txt"));
            if(read.readLine()!=null)
            {
                Oldtime=Double.parseDouble(read.readLine());
                System.out.println("Old System Time is :"+Oldtime);
            }
            else
            {
                Oldtime=0;
            }
            Process p=Runtime.getRuntime().exec("C:\\eGurkha\\lib\\vmgfiles\\win\\VmgUptimeTest.exe");
            BufferedReader rd=new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line=rd.readLine();
            System.out.println(line);
            String[] word=line.split("=");
            fileWriter=new FileWriter("C:/eGurkha/agent/sample/UptimeRecord.txt");
            fileWriter.write(word[1]);
            System.out.println("New System Time is :"+word[1]);
            System.out.println("String Written");
            fileWriter.close();         
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

    }

}

这是错误,由上面的代码显示。

Exception in thread "main" java.lang.NullPointerException
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1008)
    at java.lang.Double.parseDouble(Double.java:540)
    at com.kavi.tasks.Uptime.main(Uptime.java:17)

请告诉我这个想法......

4 个答案:

答案 0 :(得分:1)

问题是代码

if(read.readLine()!=null)
{
    Oldtime=Double.parseDouble(read.readLine());

你读行(它不是null)但是当你尝试解析时你读了下一行(并且下一行是空的)。

改为使用

String line=read.readLine();
if(line!=null)
{
    Oldtime=Double.parseDouble(line);

答案 1 :(得分:0)

if(read.readLine()!=null)
{
    Oldtime=Double.parseDouble(read.readLine());
    System.out.println("Old System Time is :"+Oldtime);
}

您正在读取if语句中的行。然后你阅读parseDouble语句中的下一行。这是引用为null。因此,您必须在if语句中保存该行。

String line = null;
if((line = read.readLine()) != null) {
    double time = Double.parseDouble(line);
    ...
}

答案 2 :(得分:0)

尝试在if语句中传递String,以便编译知道他需要传递哪种类型的对象。   如果(字符串= .... .....){

}

答案 3 :(得分:0)

问题在于

 if(read.readLine()!=null)
        {
            Oldtime=Double.parseDouble(read.readLine());
            System.out.println("Old System Time is :"+Oldtime);
        }

readLine()在内部调用lineNumber ++,这意味着在调用它时会转到文件的下一行。而是使用

 if((line = read.readLine()) != null)
        {
            Oldtime=Double.parseDouble(line);
            System.out.println("Old System Time is :"+Oldtime);
        }