Sunny
Sunny

Reputation: 615

How to get file from resource folder as File?

I want to get a file from resources folder if it exists and create it there if it doesn't. I want to access it as file. class.getResource() doesn't work as it returns an URL. class.getResourceAsStream() gives input stream, but then I can't write in it or can I somehow?

import java.io.File;
import java.io.FileNotFoundException;

public class Statistika {
File file;

public Statistika() {
    try {
        file = Statistika.class.getResourceAsStream("statistics.txt");
    } catch (FileNotFoundException e) {
        file = new File("statistics.txt");

    }
}

How to make this work?

Upvotes: 2

Views: 2809

Answers (4)

NeoP5
NeoP5

Reputation: 619

Have you tried this?

File f = new File(Statistika.class.getResource("resource.name").toURI());
if (!f.isFile()){
    f.getParentFile().mkdirs();
    f.createNewFile();
}

Upvotes: 0

Arjit
Arjit

Reputation: 3456

File f = new File("statistics.txt");
try {
        f.createNewFile();
} catch (IOException ex) { }

InputStream fis = new FileInputStream(f);

Use BufferedReader to insert contents to file referenced by f.

Upvotes: 0

Mohammad Najar
Mohammad Najar

Reputation: 2009

Don't do file = new File("statistics.txt"); in your catch block .. just do the following

try {
    File file = new File("statistics.txt");
    InputStream fis = new FileInputStream(file);
    fis = Statistika.class.getResourceAsStream(file.getName());
} catch (FileNotFoundException e) {


}

This is independent of whether the file exists or not.

Upvotes: 0

Dilip Kumar
Dilip Kumar

Reputation: 2534

Try using Statistika.class.getClassLoader().getResource(filename);
If it returns null then you can create new file/directory.
If your accessing this from jar then use Statistika.class.getClassLoader().getResourceAsStream(filename);
Hope it will solve your problem. Let me know if you found any difficulties.

Upvotes: 1

Related Questions