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

Java 创建一个读取文件的void方法,该文件可以被类中的其他方法调用?,java,file,io,void,Java,File,Io,Void,如标题所示,我想用一种方法阅读该文件。因为我不能从readFile方法返回字符串,所以我必须从getNumDash方法中获取字符串。然而,我不知道该怎么做。我希望第二个方法的返回值基于传入readFile的任何文件名。您可以为字符串使用一个非静态字段,用于存储输入文件中的文本 public class Dash { public void readFile(String fil) throws FileNotFoundException { try {

如标题所示,我想用一种方法阅读该文件。因为我不能从readFile方法返回字符串,所以我必须从getNumDash方法中获取字符串。然而,我不知道该怎么做。我希望第二个方法的返回值基于传入readFile的任何文件名。

您可以为字符串使用一个非静态字段,用于存储输入文件中的文本

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返回字符串的任何特殊原因?或者你不知道该怎么做?是的,我对@YibinLin感到不满。使用return for readFile,您可以控制文件读取是否成功。
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.
    }
}