First of all, I'm sorry if exists a similar post but I was not able to understand.
I'm trying to write a file in android and I got the following code:
String FILENAME = "hello_file.txt";
String string = "hello world!";
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Angles", "FileNotFoundException");
}catch(IOException e){
e.printStackTrace();
Log.d("Angles", "IOException");
}
I don't get any exception so I suppose it works but I'm not able to find the hello_file.txt file inside the device.
I'm running on Galaxy Nexus; no sd.
If you want to create a file in sdcard, you need to use
File f = new File (Environment.getExternalStorageDirectory(),"myfile.txt")
Related
So I'm trying to read and write to and from a file that is inside a folder within the app's directory. So the path is something like "package/userFiles/'insert file name here'" but I can't find a way to do it anywhere.
I haven't been able to test this yet but the below is the code I've got for writing a quick and simple string to the file. If you could take a look over that I would be grateful, and if at all possibly give me some direction over how to read from the file.
FileOutputStream outputStream;
File path = new File(getFilesDir(),"userFiles");
path.mkdirs();
File mypath =new File(path,newFileNameText);
try {
FileOutputStream out = new FileOutputStream(mypath);
String defaultMessage = "Empty File";
out.write(defaultMessage.getBytes());
out.close();
Intent intent = new Intent(getApplicationContext(), EditFileContents.class);
intent.putExtra(EXTRA_MESSAGE,newFileNameText);
startActivity(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can see the code starts a new activity, it is this activity from which I would like to be able to read the contents of the file.
I am trying use Android Studio emulation to produce a json in my apps. Is there a way to locate the directory and set it as path and implement it in the following?
......
DIRECTORY directory = createDummySchool();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(filepath? + "sample.json"), directory);
}catch (IOException e) {
e.printStackTrace();}
.....
well it depends where you want to write your file in, Internal or external memory.
you can always write information in internal memory which can be accessible by your app but to write on external memory you will require permission like
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
To save file internally you can use this
getFilesDir();
String filename = "myfile";
File file = new File(context.getFilesDir(), filename);
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
refer this for more information, this is the best way and should be the first place where you should be looking, :)
I used this code, but I can't find the saved file anywhere !
String filename = "fichier";
String string = "bonjour";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
You will be able to find it if you open a new fileInputStream with the same parameters as your outputStream. You might also want to consider using SharedPreferences for something as simple as storing one String.
I have a problem saving a file in android, the FileOutputStream keeps falling back to a FileNotFoundException and thus won't write the file to the external storage.
Yes I do have permission set in the manifest:
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
I've added the code below of the function, can someone explain to me what is going wrong, if it is that it is trying to overwrite an existing file, is there a way to replace that file (the name needs to be static)?
(tips on making the code look nicer are welcome as well)
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files");
if (!mediaStorageDir.exists()){
mediaStorageDir.mkdir();
}
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Kudos to Guillaume and theV0ID for leading me to the most efficient correct answer.
Below is the example code editted to the working version.
Bitmap savebitmap = Bitmap.createBitmap(drawView.getDrawingCache());
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+File.separator+"Tempsave.png");
pictureFile.getParentFile().mkdirs();
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
savebitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
Try this :
File pictureFile = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/Files"+ File.separator + "Tempsave.png");
pictureFile.getParentFile().mkdirs();
You need to create the file directories if they don't exist. If not the FileOutputStream will throw a FileNotFoundException
First off, I am not trying to write to the SDCard. I want to write some information to a file that persists between uses of the app. It is essentially a file to hold favorites of the particular user. Here is what the code looks like:
try {
File file = new File("favorites.txt");
if (file.exists()) {
Log.d(TAG, "File does exist.");
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
}
else {
Log.d(TAG, "File does not exist.");
return favDests;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
When running this code, we always get the "File does not exist." message in our DDMS log.
We have also tried the following code to no avail:
try {
File file = new File(GoLincoln.FAV_DEST_FILE);
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is this second portion of code that results in the FileNotFoundException.
I have read multiple tutorials on writing and reading files on Android and I believe I am following them pretty closely, so I am not sure why this code doesn't work successfully. I appreciate any help!
You shouldn't use the File class directly. Use Activity.getCacheDir() to get the cache dir which is specific to your application. Then use new File(cachedir, "filename.tmp") to create the file.
Preferences and SQLLite will both allow you to have persistent data without managing your own files.
To use shared preferences you grab it from your context, then you edit the values like so
mySharedPreferences = context.getSharedPreferences("DatabaseNameWhateverYouWant", 0);
mySharedPreferences.getEditor().putString("MyPreferenceName", "Value").commit();
To get a preference out
mySharedPreferences.getString("MyPreferenceName", "DefaultValue");
This is really the simplest way to do basic preferences, much easier then doing a file. More then strings are supported, most basic data types are available to be added to the Preferences class.