Java open file error: can't find the specified path - java

I try to open a .txt file (agenda.txt) from the src/resources folder, read objects from it and add them to an ArrayList, but I get this error: "The system can not find the specified path.". This is the code I use:
public void open(File f) {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(f);
ois = new ObjectInputStream(fis);
Object o;
try {
while ((o = ois.readObject()) != null) {
model.adauga((Abonat) o);
}
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(
this,
ex.getMessage(),
"Clasa...!",
JOptionPane.ERROR_MESSAGE);
return;
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(
this,
ex.getMessage(),
"Eroare deschidere fisier!",
JOptionPane.ERROR_MESSAGE);
return;
} finally {
try {
ois.close();
} catch (IOException ex) {
Logger.getLogger(CarteDeTelefonGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And in the class constructor:
private String path ="resources/agenda.txt";
File f=new File(path);
open(f);
What is wrong in the code?

the file should be located outside src, something like baseproject/resources. Thats because your path is the project base not your sources directory. Or you can change the code to
private String path ="src/resources/agenda.txt";

Related

Android app creates file but can't find it

I'm having an issue that is preventing me from releasing my app, so maybe you can help. I have this code to create and write to a file:
#Override
public void onClick (View view){
final String memoryString = memory.getText().toString();
File file = new File(getApplicationContext().getFilesDir(), filename);
FileOutputStream fos = new FileOutputStream(file);
if (location != null) {
String s = location.toString() + " " + memoryString;
Log.d(null, s);
if(fos != null) {
Log.d(null, "fos not null");
fos.write(s.getBytes());
} else {
Log.d(null, "Output Stream is null");
}
fos.close();
Log.d(null, "file created!");
}
} catch (IOException e) {
e.printStackTrace();
}
my log is saying that it's creating the file. but when I go to access and read from said file, I get the error here that it doesn't exist:
try {
File memoryFile = new File(filename);
if(memoryFile.exists()){
revealMarkers(memoryFile);
Log.d(null, "revealed");
} else {
Log.d(null, "no file found");
}
} catch (FileNotFoundException ex) {
Log.d(null, "file not found");
}
Please help if you are able, I am very much stuck
Maybe this ?
try {
File memoryFile = new File(getApplicationContext().getFilesDir(), filename);
if(memoryFile.exists()){
revealMarkers(memoryFile);
Log.d(null, "revealed");
}else{Log.d(null, "no file found");}
} catch (FileNotFoundException ex) {
Log.d(null, "file not found");
}
How is it that you created a file with this statement
File file = new File(getApplicationContext().getFilesDir(), filename);
And then try to retrieve the file with this
File memoryFile = new File(filename);
Why can't you use the same statement. How is the second statement supposed to determine the directory containing the file?

Java eclipse error with exported runnable jar file

I have a problem with an exported jar file. When I run my project in Eclipse it runs fine, but when I run it as an exported jar from the console I receive the following error message:
java.io.FileNotFoundException: firstLaunch.properties (System can't find file)
or
java.io.FileNotFoundException: resources/config/firstLaunch.properties (System can't find file)
I tried to put it in to the resource folder and change syntax from firstLaunch.properties to /resource/config/firstLaunch.properties, but again it says the same thing but with a different path. I don't know why is this doing this.
Here is the code:
public void saveConfigFile(String file, String key, String value) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(file);
// set the properties value
prop.setProperty(key, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My syntax for executing the method is
if (properties.loadConfigFile("firstLaunch.properties", "value").equals(properties.loadConfigFile("true.properties", "true"))) {
properties.saveConfigFile("port.properties", "port", "8795");
properties.saveConfigFile("ip.properties", "ip", temp[1]);
properties.saveConfigFile("firstLaunch.properties", "value", "false");
settings.port = properties.loadConfigFile("port.properties", "port");
settings.myIp = properties.loadConfigFile("ip.properties", "ip");
} else {
settings.port = properties.loadConfigFile("port.properties", "port");
settings.myIp = properties.loadConfigFile("ip.properties", "ip");
}
Your problem probably has to do with how you are referencing the file location. Add some detail/code examples as to how you are referencing the code, so then we can be sure to help. Having said that here is another way to reference a properties file:
Put it in the classpath like this:
private static Properties prop = new Properties();
private static String filename = "<name of file>.properties";
InputStream input = <ClassName>.class.getClassLoader().getResourceAsStream(filename);
try {
if (input==null) {
loggerOut.log(Level.SEVERE, "Sorry, unable to find " + filename);
}
prop.load(input);
loggerOut.info("XML In storage path: " prop.getProperty("<property in file>"));
fileNameAndPath = prop.getProperty("fileNameAndPathIN").trim();
logNameAndPath = logPath + logName;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input!=null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Update properties file values with form values

I am having a jsp file in which I load the existing values present in properties file. When the user edit the existing value and submit the form, the properties file must be updated with that values. Can anyone help me with this? I am using only java.
FileInputStream in = new FileInputStream("Example.properties");
Properties props = new Properties();
props.load(in);
Now Update it
FileOutputStream outputStream = new FileOutputStream("Example.properties");
props.setProperty("valueTobeUpdate", "new Value");
props.store(outputStream , null);
outputStream .close();
Another way of achieving same is explained at
http://crunchify.com/java-properties-files-how-to-update-config-properties-file-in-java/
PropertiesConfiguration config = new PropertiesConfiguration("/Users/abc/Documents/config.properties");
config.setProperty("Name", "abcd");
config.setProperty("Email", "abcd#gmail.com");
config.setProperty("Phone", "123456");
config.save();
here is an example of how to update your properties file :
public class PropertyManager {
private static Properties prop = new Properties();
private static String PROPERTY_FILENAME = "config.properties";
public static void main(String[] args) {
loadProperty();
System.out.println(prop.get("myProperty"));
updateProperty("myProperty", "aSecondValue");
}
public static void loadProperty(){
InputStream input = null;
try {
input = new FileInputStream(PROPERTY_FILENAME);
// load a properties file
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void updateProperty(String name, String value){
OutputStream output = null;
try {
output = new FileOutputStream(PROPERTY_FILENAME);
// set the properties value
prop.setProperty(name, value);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I let you change "new Properties", by the way you retrieve it.

Why I can't read a read only file?

I have this method supposed to read a file:
/* Read file's content */
private ArrayList<String> readFromFile() {
File file = new File("jokesBody1.bjk");
ArrayList<String> list = new ArrayList<String>();
try {
file.createNewFile();
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( file ) );
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
When I call it, it returns:
02-16 06:15:32.686: E/log activity(1380): Can not read file: java.io.IOException: open failed: EROFS (Read-only file system)
Even, if the file is read only, why I can't read it? I really can't understand what is wroong. I have this premission in my manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Can someone give me a clue? I know that I'm missing something small, but I really can't spot it.
Here is how I write the file:
/* Write content to a file */
private void writeToFile(ArrayList<String> list, Context cont) {
File file = new File("jokesBody1.bjk");
FileOutputStream fos;
if(list != null){
try {
fos = cont.openFileOutput("jokesBody1.bjk", Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
file.createNewFile();
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject("");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are trying to create the file, which of course fails on a read-only file.
Remove this line:
file.createNewFile();
This is usually used to create a new empty file before writing to it. You really don't need it if you just want to read a file that already exists.
EDIT:
Just use this:
ObjectInputStream ois = new ObjectInputStream( context.openFileInput("jokesBody1.bjk"));
Of course, you'll also have to pass a Context to the function.
You can only use File with a full path. For accessing your private files, use Context, just as you do when saving the file.
Your full function should look like:
private ArrayList<String> readFromFile(Context context) {
ArrayList<String> list = new ArrayList<String>();
try {
ObjectInputStream ois = new ObjectInputStream( context.openFileInput("jokesBody1.bjk"));
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
You aren't specifying any path:
File file = new File("jokesBody1.bjk");
So, you are not saying the app WHERE to look for the file.
Maybe, you want to search it here?
Environment.getExternalStorageDirectory()

Strange issue when creating a new file

I have the below 2 methods, supposed to read and write to a file:
/* Write content to a file */
private void writeToFile(ArrayList<String> list) {
#SuppressWarnings("unused")
File file = new File("jokesBody1.bjk");
FileOutputStream fos;
if(list != null){
try {
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject("");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* Read file's content */
private ArrayList<String> readFromFile() {
File file = new File("jokesBody1.bjk");
ArrayList<String> list = new ArrayList<String>();
try {
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( file ) );
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
When I'm calling the above methods I'm getting this error:
02-15 10:28:48.165: E/log activity(1743): Can not read file: java.io.FileNotFoundException: /jokesBody1.bjk: open failed: ENOENT (No such file or directory)
Ok, it clearly says that the file is not there, but, isn't this code supposed to create it:
File file = new File("jokesBody1.bjk");
Why I'm getting this error? I know that I'm missing something small - probably a piece of code that creates the file(I'm not sure), but as a beginner, I'm not able to spot the issue.
File file = new File("jokesBody1.bjk");
Just creates a File objects that points to that path, but no actual file.
Use
file.createNewFile();
To actually create the file.
Ok, it clearly says that the file is not there, but, isn't this code supposed to create it:
Actually, no. It only creates a File object, an then java assumes that file to exist.

Categories