Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of input a directory to Java to be proceed without wasting too much if your time.
The question is published on by Tutorial Guruji team.
The question is published on by Tutorial Guruji team.
I have a problem in here. Whenever I entered the directory path that I copy from my computer to input a txt file to my program, it always said that the file is not found. Is there something wrong from my code?
System.out.println("insert directory file = "); FileReader file = null; try { file = new FileReader(input.next()); BufferedReader readfile = new BufferedReader(file); StringBuffer sb = new StringBuffer(); try { while ((text = readfile.readLine()) != null) { sb.append(text); sb.append("n"); } readfile.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } text = sb.toString(); //System.out.println(text); System.out.println("Data entered"); System.out.println("Data length = "+text.length()+"n"); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block System.out.println("File not found. Pease insert the proper file directory.n"); }
Answer
Your code segment run just fine in my laptop. So the problem maybe here :
file = new FileReader(input.next());
Did you use your Scanner for other input before read the path? Trying changing it to
String path = input.next(); file = new FileReader(path);
And print the path when error occur to see what actually was passed to your FileReader.
catch (FileNotFoundException e1) { System.out.println("File not found. Pease insert the proper file directory.n"); System.out.println("Your input path: " + path); }
Here is the working code on my machine :
public static void main(String[] args) { String path = null; try (Scanner input = new Scanner(System.in)) { System.out.print("Input your option = "); int option = input.nextInt(); switch (option) { case 1: System.out.println("insert directory file = "); String text = ""; path = input.next(); FileReader fileReader = new FileReader(path); BufferedReader readfile = new BufferedReader(fileReader); StringBuffer sb = new StringBuffer(); try { while ((text = readfile.readLine()) != null) { sb.append(text); sb.append("n"); } readfile.close(); } catch (IOException e) { e.printStackTrace(); } text = sb.toString(); System.out.println("Data entered"); System.out.println("Data length = " + text.length() + "n"); break; default: System.out.println("There is nothing to do."); break; } } catch (FileNotFoundException e1) { System.out.println("File not found. Pease insert the proper file directory."); System.out.println("Your input path is : " + path); } }
We are here to answer your question about input a directory to Java to be proceed - If you find the proper solution, please don't forgot to share this with your team members.