Can I save own-class data to a file? - java

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?

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.

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

OutputWriter Java or Android

I want to write data to an output file and save it on a mobile device or on a computer harddrive. I am able to get my code below to work, but have to create the directory in one step and then create the file in another. Is there a more effective way to code having to create an non-existing directory before writing a file there?
Thanks
StringBuilder Path = new StringBuilder();
Path.append(Environment.getExternalStorageDirectory().toString());
String filename = "test.txt";
String test_text = "Date, Item, Quantity, Description,";
File file = new File(Path.toString()+"/" +"Test Folder2/");
file.mkdirs();
FileOutputStream file_os = null;
try {
File file2 = new File(Path.toString()+"/" +"Test Folder2", filename);
file_os = new FileOutputStream(file2);
OutputStreamWriter osw = new OutputStreamWriter(file_os);
try {
osw.write(test_text);
} catch (IOException e) {
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
Toast.makeText(QuizSettingsActivity.this, Path.toString(),
Toast.LENGTH_LONG).show();
};
String FILENAME = "test";
String string = "Date, Item, Quantity, Description,";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
For more detail on saving file on external storage follow the link mentioned below:.http://developer.android.com/guide/topics/data/data-storage.html

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.

android what is wrong with openFileOutput?

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

Categories

Resources