0

Given my project structure below, My Project structure

How do I access findLoginDetails.txt? Currently, I have

public static String getQueryFromExternalFile(final String path) {
String path1 = "src/main/resources/sql/C0001/findLoginDetails.txt";
String query = "";
try {
  BufferedReader br = new BufferedReader(new FileReader(path1));
  StringBuilder sb = new StringBuilder();
  String line = br.readLine();
  while (line != null) {
    sb.append(line);
    sb.append(System.lineSeparator());
    line = br.readLine();
  }

  query = sb.toString();
  br.close();
} catch (Throwable e) {
  query = "";
  e.printStackTrace();
}
return query;

}

But it's not working. Any idea why it's not working?

paaaaat
  • 91
  • 4
  • 12
  • 1
    Check out what path it is using : do Path p = Paths.get(path1); System.out.println(p.toAbsolutePath()); – uncaught_exception Mar 14 '16 at 03:41
  • I'm getting C:\pleiades\eclipse\src\main\resources\sql\C0001\findLoginDetails.txt So that's why it can't find the file. How do I point it to the proper directory? Basically, I just want it to search starting from the project's root directory. – paaaaat Mar 14 '16 at 03:46
  • No, it returns an error src\main\resources\sql\C0001\findLoginDetails.txt (The system cannot find the path specified) before it gets to assign a value to query. – paaaaat Mar 14 '16 at 03:54
  • Is this file meant to be altered by the user? If so, it shouldn't be in a src/resources folder, but rather in a folder on the class path. You can then add the folder to the class path either via the command line, or, in Eclipse, the class path section of the run configurations. If it's NOT configurable by the user, then you really should make src/resources a source folder. – dantiston Mar 14 '16 at 04:15

2 Answers2

2

You are better off reading it from the classpath than the project root folder. I assume the resources folder is on your build path. This will give you the portability you want.

Use

BufferedReader r = new BufferedReader(
   new InputStreamReader(MyClass.class.getClassLoader().getResourceAsStream(
     "sql/C0001/findLoginDetails")));

Where 'MyClass' is the name of your class.

See How to really read text file from classpath in Java for a better understanding.

Community
  • 1
  • 1
uncaught_exception
  • 1,068
  • 6
  • 15
0

Have you tried putting the absolute path ?

If in Windows try putting "D:\path\to\file"

Parth Joshi
  • 452
  • 4
  • 6