android what is wrong with openFileOutput? - java

I'm trying to use openFileOutput function but it doesn't compile and doesn't recognize the function. I'm using android sdk 1.6. Is this a sdk problem ? Is this a parameter problem ?
import java.io.FileOutputStream;
public static void save(String filename, MyObjectClassArray[] theObjectAr) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(theObjectAr);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}

Your method should be as follows. Takes in an extra Context as a parameter. To this method you can pass your Service or Activity
public static void save(String filename, MyObjectClassArray[] theObjectAr,
Context ctx) {
FileOutputStream fos;
try {
fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(theObjectAr);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}

You're trying invoke non-static method from static context (your method has static modifier). You either have to make your method to be non-static or to pass in an instance of Context (activity instance in most cases) and invoke the method on the object.

Also you can't openOutputStream on a path. It causes this exception:
java.lang.IllegalArgumentException: File /storage/sdcard0/path/to/file.txt contains a path separator
To fix this you need to create a file object and just create it like this:
String filename = "/sdcard/path/to/file.txt";
File sdCard = Environment.getExternalStorageDirectory();
filename = filename.replace("/sdcard", sdCard.getAbsolutePath());
File tempFile = new File(filename);
try
{
FileOutputStream fOut = new FileOutputStream(tempFile);
// fOut.write();
// fOut.getChannel();
// etc...
fOut.close();
}catch (Exception e)
{
Log.w(TAG, "FileOutputStream exception: - " + e.toString());
}

You can use openFileOutput in static Class if you pass View as below:
public static void save(View v, String fileName , String message){
FileOutputStream fos = null;
try {
fos = v.getContext().openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(message.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Unable to write to file - why?

I am attempting to save to long term file storage in android as well as create a new file in the process. This code keeps crashing with minimal helpful logcat.
Thanks.
public void save (String text) {
FileOutputStream fos = null;
try {
fos = openFileOutput("logfile.txt", MODE_PRIVATE);
fos.write(text.getBytes());
} catch (FileNotFoundException e)
{} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null)
{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I expect it to create a file called logfile.txt and print text to it but instead it crashes.
Try something alike this, in order to get a FileOutputStream from a File in tmp / private storage:
// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);
The resulting path should be /data/data/tld.domain.package/files/logfile.txt.
file.getAbsolutePath() has the value.
See Save a file on internal storage.

Can I save own-class data to a file?

I tried to save data from my own class to File! My class is
odmiana
The code looks like that:
od = new odmiana(e1.getText().toString(),e2.getText().toString(),e3.getText().toString(),e4.getText().toString(),e5.getText().toString(),e6.getText().toString());
String filename = "myfile";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(od);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Can you help me?

updating ini file in java using rest webservice

I need to update ini file in java using rest service.I could read file in browser but have no idea how to update it.Can anybody please help for the required method that would update my ini file.
dbform.java
public class dbform {
public List<db> getAlldb(){
List<db> dbList = null;
try {
File file = new File("test.ini"); // read ini file
if (!file.exists()) {
db DB = new db("dbname: test","password: test");
dbList = new ArrayList<db>();
dbList.add(DB);
savedbList(dbList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
dbList = (List<db>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return dbList;
}
private void savedbList(List<db> dbList){
try {
File file = new File("test.ini");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dbList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try to use ini4j.
The [ini4j] is a simple Java API for handling configuration files in Windows .ini format. Additionally, the library includes Java Preferences API implementation based on the .ini file.
http://ini4j.sourceforge.net/
Check your code there seems to be some issue in the way you have called the function. You don't seem to be passing the dbList into the replaceData() function. Probably it will be something like this
public void replaceData(List<db> dbList){ return DBform.savedbList(dbList); }

Clearing File content in Internal Storage on Android

I have a logging class for writing into a file in the app's internal storage space. Whenever the log file exceeds the size limit. For clearing the contents, I am closing the current FileOutputStream and creating a new stream with Write mode and closing it. Is there a way better way for accomplishing this:
public final void clearLog() throws IOException {
synchronized (this) {
FileOutputStream fos = null;
try {
// close the current log file stream
mFileOutputStream.close();
// create a stream in write mode
fos = mContext.openFileOutput(
LOG_FILE_NAME, Context.MODE_PRIVATE);
fos.close();
// create a new log file in append mode
createLogFile();
} catch (IOException ex) {
Log.e(THIS_FILE,
"Failed to clear log file:" + ex.getMessage());
} finally {
if (fos != null) {
fos.close();
}
}
}
}
You could also overwrite your file with nothing.
UPDATE:
There seems to be a better option with getFilesDir () Have a look at this question How to delete internal storage file in android?
Write empty data into file:
String string1 = "";
FileOutputStream fos ;
try {
fos = new FileOutputStream("/sdcard/filename.txt", false);
FileWriter fWriter;
try {
fWriter = new FileWriter(fos.getFD());
fWriter.write(string1);
fWriter.flush();
fWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.getFD().sync();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
In this code:
fos = new FileOutputStream("/sdcard/filename.txt", false);
FALSE - for write new content. If TRUE - text append to existing file.
public void writetofile(String text){ // text is a string to be saved
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", false); //false will set the append mode to false
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(text);
outputWriter.close();
readfromfile();
Toast.makeText(getApplicationContext(), "file saved successfully",
Toast.LENGTH_LONG).show();
}catch (Exception e) {
e.printStackTrace();
}
}

Serializing ArrayList android not working

UPDATE: After a bit of testing I've determined the file itself isnt being created, at least according to the file.exists check anyway. Any ideas?
Hi I'm trying to serialize an arraylist when my app is exited and read it back when its resumed. It doesnt seem to be creating the file.
Here is my code.
protected void onPause() {
super.onPause();
if(!myArrayList.isEmpty())
{
final String FILENAME = "myfile.bin";
try{
FileOutputStream fos;
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
//FileOutputStream fileStream = new FileOutputStream(FILENAME);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(myArrayList);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
#SuppressWarnings("unchecked")
#Override
protected void onResume() {
super.onResume();
File file = new File("myfile.bin");
if(file.exists()){
final String FILENAME="myfile.bin";
try{
FileInputStream fileStream = new FileInputStream(FILENAME);
ObjectInputStream os = new ObjectInputStream(fileStream);
myArrayList = (ArrayList<MyObject>)os.readObject();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
Any ideas? My MyObject class implements serializable.
Got it to work by changing FileInputStream fileStream = new FileInputStream(FILENAME) to FileInputStream fileStream= openFileInput(FILENAME).
os.writeObject(myArrayList);
os.flush();
os.close();
Try os.close() immediately after writeObject, it should call flush() anyways.

Categories

Resources