Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java读取文件_Java - Fatal编程技术网

使用java读取文件

使用java读取文件,java,Java,我正在尝试使用此代码读取txt文件 这是我的函数,用于读取文件: public class Open_File { public void fct(File file) throws IOException { String line = null; FileReader fr = null; { try { fr = new FileR

我正在尝试使用此代码读取txt文件

这是我的函数,用于读取文件:

public class Open_File {        
    public void fct(File file) throws IOException {    
        String line = null;
        FileReader fr = null;
        {
            try
            {
                fr = new FileReader( file );
            } 
            catch (FileNotFoundException e) 
            {  
                System.out.println( "File doesn't exists" );
                e.printStackTrace();
            }
            BufferedReader br = new BufferedReader( fr );

            try
            {
                while( (line = br.readLine()) != null )
                {
                    System.out.println( line );
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally{
                br.close();
            }
        }
    }
}
这是我的主要功能,我给出了路径:

public static void main(String[] args) throws IOException {
    Open_File o = null;
    File file= new File("C:/test.txt");
    o.fct(file);
    System.out.println("réussi");
}
问题是执行时会抛出一个
NullPointerException

Exception in thread "main" java.lang.NullPointerException
    at test.main(test.java:17)

请任何人给我一个解决这个问题的方法。

除了
null
之外,你从来没有给
o
分配任何东西。您需要更改此行:
Open\u File o=null
to
Open_File o=新建Open_File()

你说得对,它现在可以工作了,非常感谢:):)