Errors when writing object to binary - java

So, here is the code that I have:
try
{
PlayerSave save = new PlayerSave(this);
save.playerLooks = look;
File test = new File("C:/cache/" + playerName + ".tmp");
test.createNewFile();
FileOutputStream f_out = new
FileOutputStream("C:/cache/" + playerName + ".tmp");
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
obj_out.writeObject (save);
obj_out.close();
f_out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
Upon execution, I get the following error:
java.io.FileNotFoundException: C:\cache\Bobdole.tmp (The system cannot find the path specified)
I have also tried using this code:
try
{
PlayerSave save = new PlayerSave(this);
save.playerLooks = look;
// File test = new File("C:/cache/" + playerName + ".tmp");
// test.createNewFile();
FileOutputStream f_out = new
FileOutputStream("C:/cache/" + playerName + ".tmp");
ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
obj_out.writeObject (save);
obj_out.close();
f_out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
However, it produces the same error. I am confused as to why this is not working, as everything seems to be right. If you guys can figure out the problem that would be so helpful.
Thanks!!

That's telling you that the directory C:\cache does not exist. The directory must exist in order for you to be able to write files to it. You can either create it manually, or with something like:
File directory = new File("C:\\cache");
directory.mkdir();

The program can't find your folder.

Related

How to save a File to any specific path in Android

I can create file. It's creating on /data/data/com.mypackage.app/files/myfile.txt. But i want to create on Internal Storage/Android/data/com.mypackage.app/files/myfiles.txt location. How can i do this?
Codes:
public void createFile() {
File path = new File(this.getFilesDir().getPath());
String fileName = "myfile.txt";
String value = "example value";
File output = new File(path + File.separator + fileName);
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
UPDATE :
I fixed the problem. Maybe someones to helps. Only changing this line.
File output = new File(getApplicationContext().getExternalFilesDir(null),"myfile.txt");
You can use the following method to get the root directory:
File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Instead of DIRECTORY_PICTURES you can as well use null or DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, or DIRECTORY_MOVIES.
See more here:
https://developer.android.com/training/data-storage/files.html#WriteExternalStorage
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)

Keep getting cast exception error when I'm reading a data file? [duplicate]

This question already has answers here:
Why does writeObject throw java.io.NotSerializableException and how do I fix it?
(4 answers)
Closed 7 years ago.
So I'm trying to write and read a data file and declare a new variable of type 'GroceryStore' after I read the data file. I keep getting cast exception errors when I'm running my program. Could someone explain to me why this is happening and how I can fix it? Thanks.
Here's my write data file method:
{
FileOutputStream file = null;
ObjectOutputStream outStream = null;
file = new FileOutputStream(new File(filename));
outStream = new ObjectOutputStream(file);
outStream.writeObject(store1);
System.out.print(filename + " was written\n");
}
Here's my read data file method
{
FileInputStream file = null;
ObjectInputStream inStream = null;
file = new FileInputStream(new File(filename));
inStream = new ObjectInputStream(file);
GroceryStore newStore = (GroceryStore) inStream.readObject();
store1 = newStore;
System.out.print(filename + " was read\n");
}
At first glance at the code for reading it seems to want to put it to fast to the class GroseryStore, probably need some parsing before you can get it in there. Try to System.out.println the input from the reader, then you know what you have, then parse / chop and slice that into what you need / want of it.
So, second make a class for the read / write operations. As an example of how the write might work for simple text output file you could use something like this:
private String file_name = "FileName";
private String file_extention = ".txt";
BufferedWriter writer = null;
public void writeTextToFile(String stuff_to_file) {
// trying to write (and read) is a bit hazardous. So, try, catch and finally
try {
File file = new File(file_name + file_extention);
FileOutputStream mFileOutputStream = new FileOutputStream(file);
OutputStreamWriter mOutputStreamWriter = new OutputStreamWriter(mFileOutputStream);
writer = new BufferedWriter(mOutputStreamWriter);
writer.write(stuff_to_file); // and finally we do write to file
// This will output the full path where the file will be written to.
System.out.println("\nFile made, can be found at: " + file.getCanonicalPath());
} catch (Exception e) { // if something went wrong we like to know it.
e.printStackTrace();
System.out.println("Problem with file writing: " + e);
} finally {
try { // Close the writer regardless of what happens...
writer.close();
} catch (Exception e) { // yes, even this can go wrong
e.printStackTrace();
} // close try / catch
} // close finally
} // close method

Can't write my arrayList to a file as expected

I have this method, supposed to write an arrayList to a file:
private ArrayList<String> readFromFile() {
String ret = "";
ArrayList<String> list = new ArrayList<String>();
try {
InputStream inputStream = openFileInput("jokesBody.bjk");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
list.add(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
System.out.println("DA CRAZY FILE: " + ret);
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return list;
}
The problem with it is that it writes the values like [item1, item2, item3] and later when I need to load a the values back to a listArray it's loading the whole line at index 0. Now I have found the corerct way to write and read the arrayList, but I'm having troubles accessing teh file.
Here is the code I tried:
private void writeToFile(ArrayList<String> list) {
try {
FileOutputStream fos = new FileOutputStream("jokesBody.bjk");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list); // write MenuArray to ObjectOutputStream
oos.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
But it throws the following exception:
02-12 09:21:10.227: E/Exception(2445): File write failed: java.io.FileNotFoundException: /jokesBody.bjk: open failed: EROFS (Read-only file system)
Where is the mistake, where is the default app file location? I know that I'm missing something small, but as an android beginner, I'm not able to spot it.
Isn't this:
java.io.FileNotFoundException: /jokesBody.bjk: open failed: EROFS (Read-only file system)
the issue ? You're writing to a non-writeable area. Change where you're writing to (perhaps creating a temporary file would be a simple first step - I'm not familiar with Android but I assume this is possible)
Your file seems to be read only. You cannot write to a read only file!!!
I don't think you're actually saving the file where you think you are. Look at this tutorial on writing a file to external storage. A few things:
(1) You need to request permission in your manifest to write to external storage. If not you will end up with a read only situation.
(2) You need to get the external storage directory in your code before you write to it. This should be preceeded with a general check as to whether your file directory is writeable in the first place:
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
You can then create a specific directory for the files you want to store and store them in that location so you can find them later. For example:
public File getAlbumStorageDir(String albumName) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
You can then write content to the file that is returned
When you are developing for Android, you must get the OutputStream from the Context:
fos = context.openFileOutput("jokesBody.bjk", Context.MODE_PRIVATE);
An explanation about how to work with files on Android is here: Saving Files

Saving file to arraylist and writing back to file; Android

I've been trying to open a text file and and save each line as the contents of an arraylist. Once this has been completed I would like to save it back to a file. I have been running into errors for so long and have tried numerous techniques. I found that for some reason, the files themselves are not being created. It may just be a simple error I'm overlooking but if you could provide any help I will be thankful.
Here's the code:
public void addToFile(){
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations");
root.mkdirs();
File fileName = new File(root, "locationslatitude.txt");
File fileName2 = new File(root, "locationslongitude.txt");
String file = fileName.toString();
String file2 = fileName2.toString();
String theContent = Double.toString(currLatitude);
String theContent2 = Double.toString(currLongitude);
s = new Scanner(file);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
s2 = new Scanner(file2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
try {//works for latitude file
FileWriter writer = new FileWriter(file);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
//save the arraylist back to its appropriate file
try {//works for longitude file
FileWriter writer = new FileWriter(file2);
for(String str2: fileList2) {
writer.write(str2);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
}
I believe I found the answer to the problem and I wanted to post it back on here so if anyone else faces the same problem this might help them.
The problem was that it wasn't creating the file. The directory was created using "root.mkdirs();". However, the files were not created and I was trying to read from non-existing files. This is what I believe caused the error. So, in order to fix this problem I altered the code to this:
try{
s = new Scanner(fileName);
while (s.hasNext()){
fileList.add(s.next());
}
s.close();
fileList.add(theContent);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file one", Toast.LENGTH_SHORT).show();
}
}
try{
s2 = new Scanner(fileName2);
while (s2.hasNext()){
fileList2.add(s2.next());
}
s2.close();
fileList2.add(theContent2);
}catch (FileNotFoundException ex){
ex.printStackTrace();
try{
fileName2.createNewFile();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(this, "Hit IOException for file two", Toast.LENGTH_SHORT).show();
}
}
This was the only piece of code I had to alter. The code which saved back to the file worked. I hope this will be of use to someone and thanks everyone for your help.
This code works in my project. You can use it to save ArrayList contents to text file. Make sure that the directory is created beforehand. Just iterate through your list and use println method to write it to txt file.
FileWriter outFile = new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations/nameoftextfile.txt");
PrintWriter out = new PrintWriter(outFile);
out.println("PRINT LINES WITH ME");
out.print("NOT NECCESSARILY A NEW LINE");
out.close(); // at the very end
Do not forget to catch IOException.
Have you added the following permission in the AndroidManifest.xml?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Check if the file directory etc exists on the device in the first place that you are using
/appName/savedlocations Good chance these do not exist. Wrong name for appName or savedLocations. Check this using some file explorer program. Tell us if it exists. Print out the full path name of
Environment.getExternalStorageDirectory().getAbsolutePath() + "/appName/savedlocations
and see if it really exists. Just download an app for file viewing or I think you can connect to the device via eclipse as well. If you need more info on how to do it let us know. But you should first check the actual error message and report this back.
don't invent your own serialization format. java already has that.
ArrayList<String> files = ...; // whatever
// write the object to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(files);
out.close();
// read the object back
InputStream is = new FileInputStream("filename.ser");
ObjectInputStream ois = new ObjectInputStream(is);
ArrayList<String> newFiles = = (ArrayList)ois.readObject();
ois.close();

Why AccessDeniedException is raising when using just created folder?

I'm creating simple object serialization, and creation of BufferedOutputStream is raising an exception AccessDeniedException. Here is the code:
Path filePath = Paths.get("c:\\temp\\");
File xmlFile = new File("c:\\temp\\");
boolean success = xmlFile.mkdirs();
if (!success && ! xmlFile.exists() ) {
// Directory creation failed
System.out.println("Failed to create a file: " + filePath);
}
try (
ObjectOutputStream objectOut = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(filePath, StandardOpenOption.WRITE)))){
// Write three objects to the fi le
objectOut.writeObject(solarSystem); // Write object
System.out.println("Serialized: " + solarSystem);
} catch(IOException e) {
e.printStackTrace();
}
But directory is empty and if it doesn't not exist, it's created...
I'll repeat my comment here: you seem to try to write to a directory not to a file. Try changing filePath to a file instead.

Categories

Resources