java文件读取文件返回空 [英] java file reading file returning null

查看:328
本文介绍了java文件读取文件返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,该方法应该从文本文件返回一个字符串.但是它返回空值.你能帮我弄清楚这一点吗?谢谢! 这是代码

i have a method, which should return a string from a text file. But it returning null. Could you please help me to figure this one out? Thank you! Here is the code

public String findFile()
{
    String line = "";

    try 
    {
        File myDir = new File("files");
        File myFile = new File(myDir, "ISBN 123-654.txt");
        BufferedReader br = new BufferedReader(new FileReader(myFile));

        while ((line = br.readLine()) != null) 
        { 
            System.out.println(line + "1");
        } 
    }
    catch (IOException e) 
    {
        e.printStackTrace();
    }

    System.out.println(line+"2");
    return line;
}

字符串行应包含类似以下内容的文本:H:\ Java \ workspace \ LMS \ files \ book.jpg

String line should hold a text like: H:\Java\workspace\LMS\files\book.jpg

非常感谢大家的参与!这是工作代码:

many thanks to all participated! here is working code:

    public String findFile()
    {
        String line = "";
        try {
                File myFile = new File("files", "ISBN 123-654.txt");
               BufferedReader br = new BufferedReader(new FileReader(myFile));

            while ((line = br.readLine()) == null)  
                 System.out.println(line + "1");
                br.close();
             } 
             catch (IOException e) {
                 e.printStackTrace();
             }

    System.out.println(line+"2");
    return line;
    }

推荐答案

line为null时,while循环退出,因此该方法返回null.

The while loop exits when line is null, thus the method returns null.

line的值分配给循环中的另一个变量(例如,连接每行),然后返回此新变量.

Assign the value of line to another variable in your loop (or concatenate each line, for example), and return this new variable.

例如,根据您的代码:

public String findFile(){
    String fileContent = "";

    try {
        File myDir = new File("files");
        File myFile = new File(myDir, "ISBN 123-654.txt");
        BufferedReader br = new BufferedReader(new FileReader(myFile));

        String line;
        while ((line = br.readLine()) != null){ 
            System.out.println(line + "1");
            fileContent += line;
        } 
       }  
        catch (IOException e){
        e.printStackTrace();
    }
    System.out.println(fileContent+"2");
    return fileContent;
}

这篇关于java文件读取文件返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆