1

I have text file with name pwd.txt located in projectfolder->src->pwd.txt and I am accessing this file as follows:

File f1 = new File("src\\pwd.txt");
if(f1.exists()==false){
    System.out.println("file not");
}
FileReader fr = new FileReader(f1);
while ((ch = fr.read()) != -1) {
    pass = pass + (char) ch;
}
LoginForm.pwd = pass;
fr.close();

Well, let me tell you first that I am able to access this file when running within the IDE (Eclipse) but I am not able to access that filepwd.txt when I have made the jar file. When i saw the contents of that jar file, I can see the file pwd.txt

castis
  • 8,154
  • 4
  • 41
  • 63
Mohd Akram
  • 11
  • 1
  • 1
    Are you trying to read this file from within the .jar, or external to the .jar? Look up this duplicate answer of [Reading a resource file from within jar](http://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar). If external to the .jar, provide an absolute path. – KevinO Apr 18 '16 at 18:14
  • You cannot access or open files compressed in a .zip file using `File` or `FileReader` – ControlAltDel Apr 18 '16 at 18:14
  • 1
    in a jar file, you need to load this file via the classloader. getClass().getClassloader().getResource("pwd.txt") – René Winkler Apr 18 '16 at 18:17

1 Answers1

0

Try following code, i hope it will help you.

BufferedReader br = null;

//first open the file
try {
    br = new BufferedReader(new InputStreamReader(new FileInputStream("src\\pwd.txt")));
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
    return;
}

try {
    String line = br.readLine();
    while (line != null) {
        System.out.println(line);
        line = br.readLine();
    }
    br.close();
} catch (IOException e) {
    System.out.println("ERROR:"+e);
}
Roland Illig
  • 40,703
  • 10
  • 88
  • 121
theVoid
  • 743
  • 4
  • 14
  • 1
    I formatted your code so that the braces align nicely. Please do that yourself the next time. You can choose any style of braces and spaces that you want, just make it consistent. – Roland Illig Apr 18 '16 at 21:17
  • Thank you very much, i am new here so i appreciate your advice i will keep that in mind. – theVoid Apr 19 '16 at 17:58