i'm writing to you for a problem that i can't solve.
I have a Vector of Vector.
Vector<Vector<Item>> vectorItem;
I don't know how can i save it into a file, and after, how to load.
I try this:
public void save(String name, Context ctx, Vector<Vector<Item>> vectorItem) {
try {
String sdCard = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdCard + "/dir");
File file = new File(dir.getAbsolutePath(), name);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = ctx.openFileOutput(name, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(vectorItem);
oos.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
public Vector<Vector<Item>> load(String name, Context ctx) {
Vector<Vector<Item>> vectorItem; = null;
String sdCard = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdCard + "/dir");
try {
FileInputStream fis = ctx.openFileInput(name);
ObjectInputStream ois = new ObjectInputStream(fis);
vectorItem = (Vector<Vector<Item>>) ois.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return vectorSezioni;
}
But this is the error:
12-29 16:57:07.140: W/System.err(32681): java.io.IOException: open failed: ENOENT (No such file or directory)
First you must guarantee you have WRITE_EXTERNAL_STORAGE permission 'cause you're writing to the SD card.
Before the call to
File file = new File(dir.getAbsolutePath(), name);
you should call
dir.mkdirs();
to be sure the directory gets created.
Then, after you write the object to the output stream, you must flush it for all the data to get written before its closed
oos.flush();
Deserialization method should take into consideration the directory an the file name:
public Vector<Vector<Item>> load(String name, Context ctx) {
Vector<Vector<Item>> vectorItem; = null;
String sdCard = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdCard + "/dir");
File file = new File(dir.getAbsolutePath(), name);
try {
FileInputStream fis = ctx.openFileInput(file);
ObjectInputStream ois = new ObjectInputStream(fis);
vectorItem = (Vector<Vector<Item>>) ois.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return vectorSezioni;
}
Hope it helps.
Related
I am trying to copy an image from the asset folder to the sdcard but doesn't seem to copy it on first launch. It creates the folder okay but doesn't copy the file over.
prefs = getPreferences(Context.MODE_PRIVATE);
if (prefs.getBoolean("firstLaunch", true)) {
prefs.edit().putBoolean("firstLaunch", false).commit();
File nfile=new File(Environment.getExternalStorageDirectory()+"/My Images");
nfile.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("middle.jpg");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images" + filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
}
middle.jpg is the file i want to copy over. Can any one tell me what i am doing wrong?
PS i have WRITE_EXTERNAL_STORAGE in my manifest.
Thanks
You forgot to add / in the end of /My images while constructing the path
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images/" + filename);
out = new FileOutputStream(outFile);
because the filename would be MyImages+Filename so it wouldn't exists for copying.
I have a arrays of apk files, what I need is to do write the apk files of ArrayList into cache storage and read it back again as same ArrayList. I know how to insert a single file and retrieve back again from the cache. But whereas ArrayList objects as concern I completely stuck up with the solutions and methodology. Please help me. I am using following code for read and write into cache memory. Any modification or slight changes in my code will be more helpful to me. Thanks in advance
Actual code for Read and write single File
//Write to cache dir
FileWriter writer = null;
try {
writer = new FileWriter(tmpFile);
writer.write(text.toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
//Read to cache directory
String TMP_FILE_NAME = "base.apk";
File tmpFile;
File cacheDir = getBaseContext().getCacheDir();
tmpFile = new File(cacheDir.getPath() + "/" + TMP_FILE_NAME) ;
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tmpFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
Modified code for my requirement to insert ArrayList<File>
String tempFile = null;
public void writeFile(ArrayList<File> files(){
for(File file: files) {
FileWriter writer = null;
try {
writer = new FileWriter(file);
tempFile = file.getName().toString();
writer.write(file.getName().toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is where I stuck completely to read as ArrayList
What i tried is
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tempFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
I found my own answer for my question after a longstruggle from the blog.
To Write a ArrayList<File>:
public static void createCachedFile (Context context, String key, ArrayList<File> fileName) throws IOException {
String tempFile = null;
for (File file : fileName) {
FileOutputStream fos = context.openFileOutput (key, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeObject (fileName);
oos.close ();
fos.close ();
}
}
To Read a ArrayList<File>
public static Object readCachedFile (Context context, String key) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput (key);
ObjectInputStream ois = new ObjectInputStream (fis);
Object object = ois.readObject ();
return object;
}
Final code in my Activity
createCachedFile (MainActivity.this,"apk",adapter.getAppList ());
ArrayList<File> apkCacheList = (ArrayList<File>)readCachedFile (MainActivity.this, "apk");
Please help me out I am not getting the default ringtone file path.
Can any body tell how to get access to the default ringtone in Android. Here is my code for doing that thing. I have commented the path that I gave directly to asset manager to open the file and read it.
public void copyAssets() {
AssetManager assetManager = this.getAssets();
// String FileName="//media/internal/audio/media/";
File io=getFilesDir();
String[] files = null;
try {
files = assetManager.list("");
// files=assetManager.list(FileName);
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
// File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
// File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
// FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual
//
try {
in = assetManager.open("Ringtone");
// File myFolder = new File(Environment.getDataDirectory() + "/myFolder");
File myFolder = this.getDir("myFolder", this.MODE_PRIVATE);
File fileWithinMyDir=new File(myFolder,"Ringtoness");
out = new FileOutputStream(fileWithinMyDir);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
}
public void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}`
i want to make one folder on root and put txt file and append data
'
My java code
public void generateNoteOnSD(String sFileName, String sBody){
try
{
String fileName = "error";
String headings = "Hello, world!";
String path = "/data/root/";
File file = new File(path, fileName+".txt");
if (!file.exists()) {
file.mkdirs();
}
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
// Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
Log.d("file error", ""+e.getMessage());
}
}
I am getting file not found exception
Please help me how can create a file on root folder in internal storage
Try this function.
public void wrtieFileOnInternalStorage(Context mcoContext,String sFileName, String sBody){
File file = new File(mcoContext.getFilesDir(),"mydir");
if(!file.exists()){
file.mkdir();
}
try{
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
}catch (Exception e){
}
}
Try something like this -
public Boolean writeToSD(String text){
Boolean write_successful = false;
File root=null;
try {
// <span id="IL_AD8" class="IL_AD">check for</span> SDcard
root = Environment.getExternalStorageDirectory();
Log.i(TAG,"path.." +root.getAbsolutePath());
//check sdcard permission
if (root.canWrite()){
File fileDir = new File(root.getAbsolutePath());
fileDir.mkdirs();
File file= new File(fileDir, "samplefile.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write(text);
out.close();
write_successful = true;
}
} catch (IOException e) {
Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());
write_successful = false;
}
return write_successful;
}
From here - http://www.coderzheaven.com/2012/09/06/read-write-files-sdcard-application-sandbox-android-complete-example/
In this statement:
File gpxfile = new File(file, sFileName);
file should be directory (you use .txt file here).
Also, read this. You can store you file in /data/data/<your.package.name>/ dir (trying to use /data/root/ will cause Permission denied error).
Try this. Using this, I have created log file in SD card.
public void writeFile(String text){
File tarjeta = Environment.getExternalStorageDirectory();
File logFile = new File(tarjeta.getAbsolutePath()+"/", "log.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I want to serialize an object and store it inside sdcard under my project name but I'm getting FileNotFoundException.
My code is written below:
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
File dir = new File(Environment.getExternalStorageDirectory(), FILE_LOCATION + username);
try {
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, FILE_NAME);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(formList);
objectOutputStream.close();
} catch(IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
What is the reason for this issue? I'm running in emulator and my application is in android 3.0.
I suspect your filename is invalid, maybe that . in the directory? Or the file-name its self.
Correct me if I'm wrong, but don't you have to create the File before you write to it?
File file = new File(dir, FILE_NAME);
if (!file.exists()) {
file.createNewFile();
}
I would like to share my solution for this since I got a lot of help from Stackoverflow on this issue (by searching for previous answers). My solution resulted for a couple of hours of searching and piecing together solutions. I hope it helps someone.
This will write and read an ArrayList of custom objects to and from External Storage.
I have a class that provides IO to my activities and other classes. Alarm is my custom class.
#SuppressWarnings("unchecked")
public static ArrayList<Alarm> restoreAlarmsFromSDCard(String fileName,
Context context) {
FileInputStream fileInputStream = null;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();//Alarm is my custom class
//Check if External storage is mounted
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
Log.v("FileIOService", "No Such Directory Exists");
}
File file = new File(dir, fileName);
fileInputStream = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fileInputStream);
alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Do something here to warn user
}
return alarmList;
}
public static void saveAlarmsToSDCard(String fileName, ArrayList<Alarm> alarmList,Context context) {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, fileName);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(alarmList);
objectOutputStream.close();
} catch (IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
}else{
//Do something to warn user that operation did not succeed
}
}