Mohammad Abdollahzadeh
Mohammad Abdollahzadeh

Reputation: 420

how to set path for File Input Stream

i was trying to use a txt file but i got this eror "FileNotFoundException" but it was readable and it exist but on line FileInputStream i got that error whats the matter?

        System.out.println(Files.isReadable(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        System.out.println(Files.exists(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        FileInputStream f1=new FileInputStream("I:/Code/Coding/src/Files/" + path + ".txt");
        reader = new ObjectInputStream(f1);


java.io.FileNotFoundException: I:\Code\Coding\src\Files\Artists.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sample.Datebase.Server.readFiles(Server.java:70)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
Exception in thread "main" java.lang.NullPointerException
    at sample.Datebase.Server.readFiles(Server.java:94)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)

Upvotes: 2

Views: 2911

Answers (3)

Mohammad Sadegh
Mohammad Sadegh

Reputation: 747

I had the same problem and i solved it by using File class. Please try this code. maybe your problem will be solved :

File file = new File("I:/Code/coding/src/Files/" + path + ".txt");
reader = new ObjectInputStream(new FileInputStream(file));
Object o = reader.readObject();

Upvotes: 1

eigenharsha
eigenharsha

Reputation: 2231

FileNotFoundException - if the file exist but cannot be opened for reading then also throws FileNotFoundException exception

Read for Details FileInputStream

First, check the permission of that file. Is it opened for reading or not.

public static boolean isReadable(Path path): return true if the file exists and is readable but it is not guaranteed; Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for reading will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.

Upvotes: 0

sanoj mathew
sanoj mathew

Reputation: 101

The first 3 lines of this code snippet looks ok, ideally it should not throw a FileNotFoundException if the Files.exists, and Files.isReadable gives true.

But you can not use an ObjectInputStream to read a normal text file, as it will look for certain file headers to interpret the java object serialized.

Can you please copy paste the exception trace ?

Upvotes: 0

Related Questions