I'm trying to save data from the app to internal storage and load it back, but I feel like I miss something and the file is not found in the load.
Save code:
private void saveScanData(List<MyStack> surf) throws IOException {
Log.i(TAG, "Saving");
String filename = String.format("Scan%05d.data", scanNumber);
scanNumber += 1;
ObjectOutput out;
File outFile = new File(Environment.getExternalStorageDirectory(), filename);
out = new ObjectOutputStream(new FileOutputStream(outFile));
out.writeObject(surf);
out.close();
}
Load code:
public void load(View view) {
ObjectInput in;
List<MyStack> surf= null;
try {
in = new ObjectInputStream(new FileInputStream("Scan%05d.data"));
surf= (List<MyStack>) in.readObject();
in.close();
} catch (Exception e) {e.printStackTrace();}
Model model= new Model(surf);
Intent intent = new Intent(this, EditorPresenter.class);
intent.putExtra("model", model);
startActivity(intent);
}
Thank you for any help.
You write into the file with the name
String.format("Scan%05d.data", scanNumber)
But you read the file with the name
"Scan%05d.data"
Either change your object input stream creation or use another approach to create the filename.
new ObjectInputStream(new FileInputStream(String.format("Scan%05d.data", scanNumber));
Use the open openFileOutput and openfileInput method instead of opening new Input and output stream.
http://developer.android.com/intl/es/guide/topics/data/data-storage.html#filesInternal
Moreover, you are trying to save the file in the ExternalStorage folder.
Environment.getExternalStorageDirectory(). Writting in that folder requires Android permissions on the AndroidManifest
You are writing to external storage:
new File(Environment.getExternalStorageDirectory(), filename);
You are reading from nowhere:
new ObjectInputStream(new FileInputStream("Scan%05d.data"));
If you want to use external storage, use external storage in both places, not just one.
Related
I'm writing and reading from a file and it works perfectly fine. However when the activity is switched or the app is closed it appears that the file is deleted or some such as null is returned when trying to read from the file. I believed it may be because I have an onCreate blank write to the file but that should only run upon the launch to make sure the file is created. I don't mind if the file doesn't persist between launches however it should at least persist between activities.
//in oncreate is writeToHistory("");
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void btnAnsClicked(View v) throws IOException {
File path = getApplicationContext().getFilesDir();
File file = new File(path,"JWCalcHistory.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String oldAns = br.readLine();
if (!(oldAns.equals("null") || oldAns.equals(""))) {
if (Character.isDigit(readableSum.charAt(readableSum.length() - 1))) {
oldAns = "*" + oldAns;
}
UpdateSum(oldAns);
}
}
If someone can point out a way to make the contents of the file persist always until it is programmatically deleted or cleared then please let me know. The file doesn't already exist and is created upon the code being run.
You need to check if the file exists first. Something like this:
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
if(file.exists()) return;
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
file = new File(getFilesDir(), "data.txt");
try {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_APPEND);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
Is there a way to export this file so I can have access to it? I don't have a SD-card available btw.
File file = new File(Environment.getExternalStorageDirectory()+"/Download/", "yourFile.extension");
This is for downloads directory.
Then to open your file
Intent myIntent = new Intent(Intent.ACTION_VIEW);
myIntent.setData(Uri.fromFile(file));
Intent j = Intent.createChooser(myIntent, "Choose an application to open with:");
startActivity(j);
If you want to get your application path use getFilesDir() which will give you path /data/data/<your package>/files
So, you can find your file using android file manager in above mentioned directory.
From getFilesDir()
As you know, passing class types is important when programming Android applications.
One simple example is using an Intent.
Intent i = new Intent(this, MyActivity.class);
So it'll be kind of useful in some situations if I can save the class type info to a file for later use, for instance, after reboot.
void saveClassTypeInfo(Class<?> classType, String filename) {
String str = null;
// Some job with classType
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
fos.write(str.getBytes());
fos.close();
} catch (Exception e) {
}
}
If I could save in a certain way like above, then I would be able to put it back to an Intent like this in the future.
Intent i = new Intent(this, restoredClassInfoFromFile);
How I can achieve this kind of job? Because Class<?> is not an object, I don't know where to start at all.
[EDIT]
.class is an object too, so we can save it just like saving an object.
This is possible using ObjectOutputStream here SaveState is your Custom class
public static void saveData(SaveState instance){
ObjectOutput out;
try {
File outFile = new File(Environment.getExternalStorageDirectory(), "appSaveState.ser");
out = new ObjectOutputStream(new FileOutputStream(outFile));
out.writeObject(instance);
out.close();
} catch (Exception e) {e.printStackTrace();}
}
public static SaveState loadData(){
ObjectInput in;
SaveState ss=null;
try {
in = new ObjectInputStream(new FileInputStream("appSaveState.ser"));
ss=(SaveState) in.readObject();
in.close();
} catch (Exception e) {e.printStackTrace();}
return ss;
}
Full Tutorial write to File available here
And Read Object from File here
Here is I want to make. I want to make an app, for example it has a button that will download a certain video file and put it on the resource(raw) folder. Is it possible?
Short answer : You can not.
You can not, under any circumstance, write/dump a file to the raw/assets folder in runtime.
What you can do is to download the video and store it into Internal Memory (application reserved storage) or External Memory (usually your SDCard))
For example, you can store media files, for instance a Bitmap to your external storage like this.
private void saveAnImageToExternalMemory(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "yourimagename.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And equally, read an file, in this example an image (which is then loaded to an imageView), from external memory
private void loadImageFromStorage(String path){
try {
File f=new File(path, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Edit: Additionally, you can store your data into internal memory
Alternatively you can also save the Bitmap to the internal storage in
case the SD card is not available or for whatever other reasons you
may have. Files saved to the internal storage are only accessible by
the application which saved the files. Neither the user nor other
applications can access those files
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = context.openFileOutput("yourimage.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
Check this documentation for more information
Regards,
I have a Java form in which you can select a file to open. I have that file:
File my_file = ...
I want to be able to save my file as a different name.
how can I do it using "File my_file"?
I tried:
File current_file = JPanel_VisualizationLogTab.get_File();
String current_file_name = current_file.getName();
//String current_file_extension = current_file_name.substring(current_file_name.lastIndexOf('.'), current_file_name.length()).toLowerCase();
FileDialog fileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
fileDialog.setFile(current_file_name);
fileDialog.setVisible(true);
But that doesn't save the file.
I would recommend using the Apache Commons IO library to make this task easier. With this library, you could use the handy FileUtils class that provides many helper functions for handling file IO. I think you would be interested in the copy(File file, File file) function
try{
File current_file = JPanel_VisualizationLogTab.get_File();
File newFile = new File("new_file.txt");
FileUtils.copyFile(current_file, newFile);
} catch (IOException e){
e.printStackTrace();
}
Documentation
If you want to copy it with a different name, i found this piece of Code via google
public static void copyFile(File in, File out) throws IOException {
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
now you can call it with
File inF = new File("/home/user/inputFile.txt");
File outF = new File("/home/user/outputFile.txt");
copyFile(inF, outF);
it´s just important that both Files exist, otherswise it will raise an exception
You can rename the file name.
Use:
myfile.renameTo("neeFile")
There is a Method called renameTo(new File("whatever you want")); for File Objects