创建一个读取文件的void方法,该方法可以被类中的其他方法调用?

时间:2015-10-02 22:19:16

标签: java file io void

public class Dash {
    public void readFile(String fil) throws FileNotFoundException {
        try {
            Scanner input = new Scanner(new File(fil));
            String text = input.next();
            input.close();
        } catch (FileNotFoundException e) {
        }
    }

    public int getNumDashes() throws FileNotFoundException {
        readFile(fil);
        String text = input.next();
        // code to find number of dashes from the string of the read file.
    }
}

如标题所示,我想用一种方法读取文件。由于我无法从readFile方法返回字符串,因此我必须从getNumDashes方法中获取字符串。但是,我不知道该怎么做。我希望我的第二个方法的返回值基于传递给readFile()的文件名。

1 个答案:

答案 0 :(得分:0)

您可以为字符串使用非静态字段,您可以在其中存储输入文件中的文本。

public class Dash {
    String text;
    public void readFile(String fil) throws FileNotFoundException {
        try{
            Scanner input = new Scanner (new File(fil));
            text= input.next();
            input.close();
        }
        catch (FileNotFoundException e){
        }

    public int getNumDashes() throws FileNotFoundException {
        readFile(fil);
        // You can read from the field *text* here and process the input
        // code to find number of dashes from the string of the read file.
    }
}