smoothsipai smoothsipai - 6 months ago 16
Java Question

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

here are the two java classes:

to get the input file:

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


to parse the input file:

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


all i get is FileNotfound Exception for filename.
I tried to using the string name but i couldn't get the string name from inputfile class using getters but i failed. can someone tell me how to do this?

Thanks a ton.

Answer

You can define your getFileName method in your Inputfile class

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

And then you can use above defined method in main method of PdfParse class

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

Hope this helps.