繁体   English   中英

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

[英]How to use FileInputStream for accessing an input file from another class?

这是两个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异常。 我尝试使用字符串名称,但是我无法使用getters从inputfile类中获取字符串名称,但是我失败了。 有人可以告诉我该怎么做吗?

万分感谢。

你可以定义你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;
    }
}

然后可以在PdfParse类的main方法中使用上面定义的方法

  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();
         .........   
      } 
  }

希望这可以帮助。

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

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);
        ...
    }

} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM