I have managed to save two separate pieces of information in the file below. But I would love to know how I can go about editing the info in this file.
try {
RandomAccessFile fileWriter = new RandomAccessFile("Officers.txt", "rw");
fileWriter.seek(fileWriter.length());
fileWriter.writeUTF(officerObject.getOfficerBadgeNum());
fileWriter.writeUTF(officerObject.getOfficerFirstName());
fileWriter.writeUTF(officerObject.getOfficerLastName());
fileWriter.writeUTF(officerObject.getOfficerPrecint());
fileWriter.close();
System.out.println("Data Successfully Saved");
}
catch (IOException e) {
System.out.println("Error in File. Could not SAVE Officer");
e.printStackTrace();
}
Related
I'm trying to save user information in a single save file in local directory. However every time I run the app, the information doesn't save--I can tell by rerunning the app and the file data isn't updated or returning to the activity and finding out the data displayed isn't updated upon returning to the same activity. Here is the function in the activity where I set up a file output stream and decided to write in the information through a string containing all the User information and display "FILE CLOSED" once I assumed the file has written. Could you spot any missing steps or anything that I missed so that the file can be written?
public void saveToFile() throws FileNotFoundException{
//new filestream
FileOutputStream fostream;
fostream = openFileOutput(fileName, Context.MODE_PRIVATE);
//Write into file for each User in Array
for (int i = 0; i < userArrayList.size(); i++){
String contents = userArrayList.get(i).display();
System.out.println(userArrayList.get(i).display());
try {
fostream.write(contents.getBytes());
} catch (IOException e) {
System.out.println("NOTHING WRITTEN");
e.printStackTrace();
}
}
try {
fostream.close();
System.out.println("FILE CLOSED");
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks so much for your help!
Currently I'm developing an android app where the user has to click on a button this adds +1 to a count. After 100 there is another button which causes a reset of the count and increase the level and difficulty which is stored in another 2 "ints". Well its all working but I seriously have big problems with creating a save file.
-I gave me the permission via AndroidManifest.xml
-Tryed 3 other code examples
I did import everything that is necessary and the rest of the code is working
There has to be a mistake in this part of my code:
(my part for the Saving the "Stats")
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileOutputStream savelvl = openFileOutput("savelvl.data", Context.MODE_PRIVATE);
savelvl.write(level);
savelvl.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
can anyone suggest an improvement to the code or tell me the mistake in saving the file to the internal storage?
I've had success with using a BufferedWriter instead of FileOutputStream, although I'm sure it could given a different setup. Below is some code with "FileOutputStream out", which I was trying to use initially, commented out.
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file,true));
//out = new FileOutputStream(file);
Log.i("file","file opened");
writer.write(someString);
//out.write(someString.getBytes());
Log.i("file","file written");
} catch (Exception e) {
Log.e("fileNotFound","file not found exception");
e.printStackTrace();
}/*
try {
out.write(someString.getBytes());
Log.i("file","file written");
Log.i("str2File",someString.getBytes().toString());
} catch (IOException e) {
Log.e("fileWrite","file write error");
e.printStackTrace();
}*/ finally {
try {
//out.getFD().sync();
//out.close();
writer.close();
Log.i("file","file closed");
} catch (Exception e) {
Log.e("closeError","error closing file");
e.printStackTrace();
}
}
You cannot flush your data. When you use writer you must call flush method after write method.
OutputStrem stream = ... // I cannot create new reference because "OutStream" class is abstract
stream.write(data, offset, length);
stream.flush();
stream.close();
I am using the following method to read from the internal storage:
private void deserialize(ArrayList<Alias>arrayList) {
try {
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
arrayList = (ArrayList<Alias>)ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
It reads the content of the file "filename" to the "arrayList".
The "serialize" method is as follows:
void serialize(ArrayList<Alias>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is that I whenever I run my program again, the "arrayList" is empty. So I guess I am opening the file in wrong input mode.
My aim is to first get the array from the file, then modify it within the app, and then write the modified array back to the file.
Can someone please help me with my problem?
Thanks!
Can you post your pice of your source code? I think the way which you used to parse file content get issue.
Read here:
Android ObjectInputStream docs
I read that the method readObject() read the next object...i this that you must iterate with something like this:
MediaLibrary obj = null;
while ((obj = (MediaLibrary)objIn.readObject()) != null) {
libraryFromDisk.add(obj);
}
I know that this is a widely discussed question , but I am really confused with those examples provided on android developers manual .
So , I have a "source.txt" in my res/raw folder .For example I want to write 2 lines in it(for ex. Hello\nWorld) and then read them from another activity. Can anyone write the source code for this , please.
You should replace your .txt file to your extornal or internal storage.And You must give permission for write text from androidManifest.xml
for reading file you can do this
public String readFile(String filePath) {
String jString = null;
StringBuilder builder = new StringBuilder();
File yourFile = new File("/sdcard/" + filepath);
if (yourFile.exists()) {
Log.i("file", "file founded");
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(yourFile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String row = "";
try {
while ((row = bufferedReader.readLine()) != null) {
builder.append(row + "\n");
}
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jString = builder.toString();
}
else {
Log.i("FAIL", "FILE NOT FOUND");
}
return jString;
}
for writing file you can use this
public void writetoFile(String filename,String text) {
File file = new File("/sdcard/" + filename);
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileWriter fileWriter;
try {
//you can change second parametre true or false this is about append or clean and write
fileWriter = new FileWriter(file, false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.append(jsonText);
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Whatever is in your APK file is read-only, therefore you are unable to write to file stored in res/raw source folder as it is still in your APK. if you want to work on file shipped with your app, you need to copy if to internal storage or SD card from APK first so that would allow you to alter the content.
Every file in your apk is read only, so you need to create the file in your internal storage or SD Card. If you just want to send small amount to of data to second activity, you can send data along with intent or use sharedPreference.
If you really want to read and write data to/from SD card then you need to use FileInputStream and OutputStreamWriter to read/write data to a file. Check this tutorial here to see how it's done. http://www.java-samples.com/showtutorial.php?tutorialid=1523
Well, first of all, I'm just learning and don't quite understand what I'm doing.
What I want is to create an Excel file in memory and then it would be possible to send it with ActionBarSherlock's ShareActionProvider to mail for example.
But I got exeption :
11-24 18:45:52.112: W/System.err(22073): java.io.FileNotFoundException: /Competition.xls: open failed: EROFS (Read-only file system)
As I searched for the answer on the web - it's the problem of file being created in the system area which is read-only. But I want to create it in memory.. Somehow. Once again, I don't really understand well how it works - the way I see it - I create .xls file somewhere in the memory. So the explanation would be helpful.
So, here's the code :
private void createFileTosend() {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
File toSend=null;
try {
toSend = getFile();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
inputStream = new BufferedInputStream(new FileInputStream(toSend));
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
/* ignore */
}
try {
outputStream.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
public File getFile() throws IOException, WriteException{
File file=new File("Competition.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
//then goes creation of Excel 's xls file which is not important for the question
workbook.write();
workbook.close();
return file;
}
Once again, don't downvote me, please, I'm just learning
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ass per the error log you post, i guess you didn't read it carefully. IT is saying read only file system. You need to put the above permission ATLEAST in your android manifest.
Do this much and see if there is any more error or not
I have a doubt may be wrong
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
you are using Context.MODE_WORLD_READABLE its readable, so how can you access it in write mode later. Is it right?
Check this link
Use the http://developer.android.com/guide/topics/data/data-storage.html to clear your doubt about file creation