The program runs well with getResource, but after made it into the jar file, it has FileNotFoundException. It cannot find out test.conf.
My code is
URL url = getClass().getResource("test.conf");
File fin = new File(url.getPath());
FileInputStream fis = null;
try {
fis = new FileInputStream(fin);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I think I can fix the problem by using getResourceAsStream. But I'm not sure how to change getResource to getResourceAsStream.
Your example suggests that your reading code already works on a FileInputStream. You should be able to make it work with the more general InputStream. This will allow you to just pass the result of getResourceStream() to your reading code, without having to worry about Files.
So:
URL url = getClass().getResource("test.conf");
File fin = new File(url.getPath());
FileInputStream fis = new FileInputStream(fin);
ReadResourceFromStream(fis);
Changes to:
InputStream is = getClass().getResourceAsStream("test.conf");
ReadResourceFromStream(is);
Related
I am using a property file for some configurable values. But I do not know why I can read the property value but when I want to update the existing or write a new key/value pair it is not working
Properties props = new Properties();
try
{
String key = "maxHolidays";
File file = ResourceUtils.getFile("classpath:config.properties");
InputStream in = new FileInputStream(file);
props.load(in);
String maxHolidays = (String) props.get(key);
System.out.println(maxHolidays);
props.setProperty("newkey", "newvalue");
OutputStream out = new FileOutputStream(file);
props.store(out, null);
I finally found the solution. All answers here were basically not right. It is possible to change a property file during runtime. The only mistake I made was not closing the Inputstream when opening the Outputstream. Here is the code that worked for me.
File file = ResourceUtils.getFile("classpath:First.properties");
FileInputStream in = new FileInputStream(file);
Properties props = new Properties();
props.load(in);
System.out.println(props.getProperty("country"));
in.close();
FileOutputStream out = new FileOutputStream(file);
props.setProperty("country", "germany");
props.store(out, null);
System.out.println(props.getProperty("country"));
out.close();
But what is really annoying that no Exception was thrown. That cost me 3 days to solve this issue. Operating system seems to block writing to file when InputStream is still open. But again I expect some exception to be thrown what is not the case.
This should works,
Properties props = new Properties();
try {
String key = "maxHolidays";
File file = ResourceUtils.getFile("file:config.properties");
InputStream in = new FileInputStream(file);
props.load(in);
String maxHolidays = (String) props.get(key);
System.out.println(maxHolidays);
props.setProperty("newkey", "newvalue");
OutputStream out = new FileOutputStream(file);
props.store(out, null);
} catch (IOException e) {
e.printStackTrace();
}
put your config.properties in the root of your project folder
I have a working code (at least in eclipse), in which I work with some files: I have a .dot file I write into some text, so I can read it to create a graph. Then I save the graph into a .png image, which I display on a frame..
My problem is: In the executable .jar file I can´t acces these files, and also - if i know it right - I can´t even change em runtime. So I tried to work with Streams. I can access the .dot file like:
$InputStream fileStream = this.getClass().getResourceAsStream("/graf.dot");$
But I have no clue how can i write into it. I found OutputStreamWriter, but it also requires a path, which I can´t acces like I accessed the InputStream..I also struggle with reading the text from the file and creating the .png file... Can you please help me? Is it even possible to work with these files at runtime?
I had the same problem accessing the background image of the frame, but I found a solution:
$URL bgPath = this.getClass().getResource("/background.jpg");
panel = new JLabel(new ImageIcon(bgPath));$
So I really hope there exists some similar solution for the files I work with..
private void createGraph() throws IOException {
/* Creating the graph into "graf.dot" file.
* The format is in DOT language.
*/
String fileName = "src/main/resources/graf.dot";
InputStream fileStream = this.getClass().getResourceAsStream("/graf.dot");
BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));
/* Here I write the content into *graph_string**/
br.close();
try {
FileOutputStream outputStream = new FileOutputStream(fileName);
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
//FileWriter writer = new FileWriter(fileName);
writer.write(graph_string);
writer.close();
}catch (IOException e) {
System.out.println("Error writing into file");
}finally {
drawGraph();
}
}
private void drawGraph() throws IOException {
/*
* Reading the graph from file for visualization
*/
String fileName = "src/main/resources/graf.dot";
InputStream fileStream = this.getClass().getResourceAsStream("/graf.dot");
BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));
File file = new File("src/main/resources/graf.dot");
String str="";
try {
str = FileUtils.readFileToString(file, "UTF-8");
} catch (IOException e) {
System.out.println("Errorrr reading from file.");
}
MutableGraph g = Parser.read(str);
Graphviz.fromGraph(g).render(
Format.PNG).toFile(new File("src/main/resources/graph.png"));
BufferedImage background = ImageIO.read(new File("src/main/resources/graph.png"));
panel = new JLabel(new ImageIcon(background));
...
}
I'm trying to create sub directories in my apps cache folder but when trying to retrieve the files I'm getting nothing. I have some code below on how I created the sub directory and how I'm reading from it, maybe I'm just doing something wrong (well clearly I am lol) or maybe this isn't possible? (though I haven't seen anywhere that you can't). thank you all for any help!
creating the sub dir
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
File file2 = new File(file, each_filename);
Toast.makeText(getApplicationContext(), file2.toString(), Toast.LENGTH_SHORT).show();
stream = new FileOutputStream(file2);
stream.write(bytes);
reading from it
File file = new File(context.getCacheDir(), "SubDir");
File newFile = new File(file, filename);
Note note;
if (newFile.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = new FileInputStream(new File(file, filename));
ois = new ObjectInputStream(fis);
note = (Note) ois.readObject();
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return note;
}
I've also tried with this and nothing
String file = context.getCacheDir() + File.separator + "SubDir";
I don't see anywhere in the code you posted where you actually create the sub-directory. Here's some example code to save a file in a sub-directory, by calling mkdirs if the path doesn't yet exist (some parts here need to be wrapped in an appropriate try-catch for an IOException, but this should get you started).
File cachePath = new File(context.getCacheDir(), "SubDir");
String filename = "test.jpeg";
boolean errs = false;
if( !cachePath.exists() ) {
// mkdir would work here too if your path is 1-deep or
// you know all the parent directories will always exist
errs = !cachePath.mkdirs();
}
if(!errs) {
FileOutputStream fout = new FileOutputStream(cachePath + "/" + filename);
fout.write(bytes.toByteArray());
fout.flush();
fout.close();
}
You need to make your directory with mkdir.
In your code:
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
file.mkdir();
File file2 = new File(file, each_filename);
So I've been doing like the simplest thing ever. Create a text file for a Java application. Just directly in the C directory:
File file = new File("C://function.txt");
System.out.println(file.exists());
The file never shows up though, I changed the slashes, changed the path, nothing. Could anyone help me out here?
There are many methods to create a new file with java : (You should firstly verify the permission to create a file in that folder c: )
String path = "C:"+File.separator"function.txt";
File f = new File(path);
f.mkdirs();
f.createNewFile();
__ or
try {
//What ever the file path is.
File f = new File("C:/function.txt");
FileOutputStream is = new FileOutputStream(f);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("Line 1!!");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file function.txt");
}
After Java 7, you should use the new I/O API instead of the File class to create new files.
Here is an example:
Path path = Paths.get("C://function.txt");
try {
Files.createFile(path);
System.out.println(Files.exists(path));
} catch (IOException e) {
e.printStackTrace();
}
You are just creating a File object, not a file itself. So in-order to create new file you need use below command:
file .createNewFile();
This would create your file under C:\ drive. Maybe you can also check if it is already exsits and handle exception etc.
If the file is not exist you can create a new file like:
if(!file.exists()) {
try {
file.createNewFile();
System.out.println("Created a new File");
} catch (IOException e) {
e.printStackTrace();
}
}
The simplest way to do this:
String path = "C:"+File.separator+"function.txt";
File file = new File(path);
System.out.println(file.exists());
try this:
File file = new File("C://function.txt");
if (!file.isFile())
file.createNewFile();
Try this
File file = new File("C:/test.text");
f.createNewFile();
how to check if file exists and open it?
if(file is found)
{
FileInputStream file = new FileInputStream("file");
}
File.isFile will tell you that a file exists and is not a directory.
Note, that the file could be deleted between your check and your attempt to open it, and that method does not check that the current user has read permissions.
File f = new File("file");
if (f.isFile() && f.canRead()) {
try {
// Open the stream.
FileInputStream in = new FileInputStream(f);
// To read chars from it, use new InputStreamReader
// and specify the encoding.
try {
// Do something with in.
} finally {
in.close();
}
} catch (IOException ex) {
// Appropriate error handling here.
}
}
You need to create a File object first, then use its exists() method to check. That file object can then be passed into the FileInputStream constructor.
File file = new File("file");
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
}
You can find the exists method in the documentation:
File file = new File(yourPath);
if(file.exists())
FileInputStream file = new FileInputStream(file);