Saving file to arraylist and writing back to file; Android - java

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();

Related

Text file give error - Transfer error: No such file or directory - DDMS

I'm trying to pull my text file which the name of the file was programmed according to the title of an article which is MACC is on the right track, let’s hope it will go all the way.txt but on pull it gives me this error :
[2016-08-29 11:59:06 - ddms] transfer error: No such file or directory
[2016-08-29 11:59:06] Failed to pull selection: No such file or directory
When I try to delete
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:206)
at com.android.ddmlib.JdwpPacket.movePacket(JdwpPacket.java:235)
at com.android.ddmlib.Debugger.sendAndConsume(Debugger.java:347)
at com.android.ddmlib.Client.forwardPacketToDebugger(Client.java:707)
at com.android.ddmlib.MonitorThread.processClientActivity(MonitorThread.java:344)
at com.android.ddmlib.MonitorThread.run(MonitorThread.java:263)
my source code
public void storeHTML(Context context, ArrayList<String> storeHTML) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "voicethenews");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, storeHTML.get(0) + ".txt");
FileWriter writer = new FileWriter(gpxfile);
//BufferedWriter bufferedWriter = new BufferedWriter(writer);
for(int i = 1; i < storeHTML.size(); i++) {
//bufferedWriter.newLine();
writer.append(System.getProperty("line.separator") + storeHTML.get(i));
}
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
I've searched high and low for the answer put still didn't manage to solve it. Thank you.
Please test this code:
Environment.getExternalStorageDirectory().getAbsolutePath()+ "/SOME_DIRECTORY"

java.nio.file.AccessDeniedException when reading a file

I want to read file content using this code:
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
On some systems this file is not present or it's empty. How I catch this exception? I want to print message "No file" when there is no file and there is no value.
The AccessDeniedException can be thrown only when using the new file API. Use an inputStream to open a stream from the source file so that you could catch that exception.
Try with this code :
try
{
final InputStream in = new Files.newInputStream(Path.get("/sys/devices/virtual/dmi/id/chassis_serial"));
} catch (FileNotFoundException ex) {
System.out.print("File not found");
} catch(AccessDeniedException e) {
System.out.print("File access denied");
}
Try to use filter file.canRead()) to avoid any access exceptions.
Create a File object and check if it exists.
If it does then it's safe to convert that file to a byte array and check that the size is greater then 0. If it is convert it to a String. I added some sample code below.
File myFile = new File("/sys/devices/virtual/dmi/id/chassis_serial");
byte[] fileBytes;
String content = "";
if(myFile.exists()) {
fileBytes = File.readAllBytes(myfile.toPath);
if(fileBytes.length > 0) content = new String(fileBytes);
else System.out.println("No file");
else System.out.println("No file");
I know it's not the one liner you were looking for. Another option is just to do
try {
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
} catch(Exception e) {
System.out.print("No file exists");
}
Read up on try catch blocks here like MrTux suggested, as well as java Files and java io here.

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

Filewriter issues - Java Android

My filewriter does not seem to create a file. This is my code:
public void peopledetails_write(ArrayList<PeopleDetails> peopledetails_file) {
////numbers is the arraylist of numbers.
///names is the arraylist of names of people.
///Written to file like 01235 678 908, Daniel; 01245 645 123, Bob Marley; etc.
///Like a CSV file.
try{
FileWriter writer_file = new FileWriter("PeopleDetailsFile");
String filestring = ""; ///initializes filestring, which is written to the file.
for(PeopleDetails person : peopledetails_file){
String person_detail_string = "";
person_detail_string = person.name + "," + person.number;
filestring = filestring + person_detail_string + ";";
}
writer_file.write(filestring);
writer_file.close();
}
catch (IOException e) {
Log.e("ERROR", e.toString());
}finally{
///Hopefully won't get an error here.
Intent switch_menu = new Intent(this, MenuList.class);
startActivity(switch_menu);
}
}
It acts on the finally, and takes the user back to the main menu of my app. I have managed to debug the section where this code is, and reckon that this is faulty code, as I get a FileNotFound exception, after this section should have written a file.
What is wrong with this code?
here where your going wrong, unless api points to some specific directory, you should always
use absolute file path(complete file path).
FileWriter writer_file = new FileWriter(complete_file_path);

Writing to a File in Java

I'm really new to Java, and I can't write to a file for some reason, my code looks like this:
FileWriter fstream;
try {
fstream = new FileWriter(fileLocation);
BufferedWriter out = new BufferedWriter(fstream);
log.info("test was supposed to be written to the file");
out.write("test");
out.flush();
out.close();
} catch (IOException e) {
log.error("File not created ", e);
}
When I go to the fileLocation, I see my file, but it's empty. My log does say "test was supposed to be written to the file"
What could I be doing wrong here?
Thanks!
UPDATE: My FileLocation variable is a string:
private String fileLocation="/Users/s/out.txt";
I'm using a Mac
Code is fine. Are you checking the right file location? Perhaps you had created the file you're checking before; while your program could be writing elsewhere.

Categories

Resources