如何使用FileInputStream访问另一个类的输入文件?

时间:2016-05-10 09:00:21

标签: java input file-io inputstream user-input

这是两个java类:

获取输入文件:

public class Inputfile {    

public static void main(String[] args) throws Exception  {
    Scanner sc = new Scanner(System.in);
    Scanner input = null;
    boolean isFile = false;
    while (isFile == false){   
        System.out.print("Input file name? ");
        String fileName = sc.next();

        File inputFile = new File(fileName);
        if (inputFile.exists()){
            input = new Scanner(inputFile);
            isFile = true;
        }            
    } 

解析输入文件:

public class PdfParse {

public static void main(final String[] args) throws Exception  {



Inputfile inputfile = new Inputfile();
 String fileName;
 fileName =  inputfile.toString();      
  FileInputStream inputstream = new FileInputStream(new File("fileName"));


ParseContext pcontext = new ParseContext();
  .........   
  } 

我得到的是FileNotfound文件名异常。 我试图使用字符串名称,但我无法使用getter从inputfile类中获取字符串名称,但我失败了。谁能告诉我怎么做?

非常感谢。

2 个答案:

答案 0 :(得分:2)

您可以在getFileName班级

中定义Inputfile方法
 public class Inputfile {    

      public static String getFileName() throws Exception  {
        Scanner sc = new Scanner(System.in);
        String fileName = null;
        boolean isFile = false;
        while (!isFile){   
            System.out.print("Input file name? ");
            fileName = sc.next();

            File inputFile = new File(fileName);
            if (inputFile.exists()){
                isFile = true;
            }            
        } 
        return fileName;
    }
}

然后,您可以在main

PdfParse方法中使用上面定义的方法
  public class PdfParse {

      public static void main(final String[] args) throws Exception  {



        String fileName = InputFile.getFileName();

        FileInputStream inputstream = new FileInputStream(new File(fileName));


         ParseContext pcontext = new ParseContext();
         .........   
      } 
  }

希望这有帮助。

答案 1 :(得分:1)

您可以将文件传递给第二个类:

Scanner sc = new Scanner(System.in);
File inputFile = null;
while (inputFile == null){   
    System.out.print("Input file name? ");
    String fileName = sc.next();

    inputFile = new File(fileName);
    if (!inputFile.exists()){
        inputFile = null;
    }            
}

PdfParse.parse(input); // <-- Pass file to parser

然后你的PdfParse课程看起来像这样:

public class PdfParse {

    public static void parse(File inputFile) throws Exception {
        FileInputStream inputstream = new FileInputStream(inputFile);
        ...
    }

}