So many examples for this question. I tried and still doesn't work.
Test.txt file is created. But no data is written into the test.txt file.
What is wrong with my code? I have permission in the Manifest file as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Code:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();
Cause, you are creating file in SDCard but writing in Internal Storage. Try as follows...
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();
From the doc openFileOutput will
Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.
those files are under the.
data > data > your app id > files
but your file is not in internal folder its in external storage..
Change this line
fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
into
fos=new FileOutputStream(file);
And try..
Related
I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?
// create file
public void createfile(String name)
{
try
{
new FileOutputStream(filename, true).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// write to file
public void appendToFile(String dataAppend, String nameOfFile) throws IOException
{
fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
fosAppend.write(dataAppend.getBytes());
fosAppend.write(System.getProperty("line.separator").getBytes());
fosAppend.flush();
fosAppend.close();
}
Here's an example from my code:
try {
String filename = "abc.txt";
File myFile = new File(Environment
.getExternalStorageDirectory(), filename);
if (!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = string.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And don't forget the:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try like this,
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
File file = new File(newFolder, "MyTest" + ".txt");
file.createNewFile();
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
} catch (Exception e) {
System.out.println("e: " + e);
}
It's pretty easy to create folder and write file on sd card in android
Code snippet
String ext_storage_state = Environment.getExternalStorageState();
File mediaStorage = new File(Environment.getExternalStorageDirectory()
+ "/Folder name");
if (ext_storage_state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
if (!mediaStorage.exists()) {
mediaStorage.mkdirs();
}
//write file writing code..
try {
FileOutputStream fos=new FileOutputStream(file name);
try {
fos.write(filename.toByteArray());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//Toast message sd card not found..
}
Note: 'getExternalStorageDirectory()'
actually gives you a path to /storage/emulated/0 and not the actual sdcard
'String path = Syst.envr("SECONDARY_STORAGE");' gives you a path to the sd card
I would like to store my string values as a text file and hence i declared like
String item1, item2;
//code...
item1=arraylist.getItem1();
item2=arraylist.getItem2();
FileOutputStream fos;
try {
fos = openFileOutput(item1, Context.MODE_PRIVATE);
fos.write(item2.getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//code....
But am getting an error of
1)java.lang.illegalargumentexception file contains a path separator
and my textfile in data/data/my package dir couldn't be opened and displays a message of
opendir failed permission denied android adb
What am doing wrong here and how can i store and see the values of my string in a text file.
1) java.lang.illegalargumentexception file contains a path separator
openFileOutput() doesn't accept paths, only a file name. If you want to create a file using a path try:
BufferedWriter writer;
try {
File file = new File(filePath);
FileWriter fileWriter = new FileWriter(file);
writer = new BufferedWriter(fileWriter);
...
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2) opendir failed permission denied android adb
In android you cannot access files in in your phone. If you need to access the file then you need to save it somewhere accessible such as SD card.
Finally i resolved this issue. I created a new class and instantiated this class in the previous class and my codings are:
public void Class1(String item1, String item2, Context context)
{
FileOutputStream fos;
try {
fos = context.openFileOutput("newfile.txt", Context.MODE_PRIVATE);
fos.write(item1.getBytes());
fos.write(item2.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and i instantiated this class as
Class1 main = new Class1();
tracklog.Logger(item1, item2,this);
Hence illegal argument exception error got resolved. Hope this may help someone :-)
I want to save an image from the drawable directory to the download folder in the phone.
The code I was trying is:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tradoficial);
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String fileName = "test.jpg";
File dest = new File(sd, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But nothing happens on my phone. Is there anything wrong?
Thanks a lot!
in the AndroidManifest.xml file, add <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> under the <manifest> tag
I am able to write and then read a text file in the SAME activity, but I am unable to read a text file after writing to it from another Activity.
Ex: Activity A creates and writes to a text file. Activity B reads that text file.
I use this code to write to the text file in Activity A:
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try
{
fos = openFileOutput("user_info.txt", Context.MODE_WORLD_WRITEABLE);
osw = new OutputStreamWriter(fos);
osw.write("text here");
osw.close();
fos.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And then I use this code to try and read the same text file created by Activity A, but I get a FileNotFoundException:
try
{
FileInputStream fis = openFileInput("user_info.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader buff = new BufferedReader(isr);
String line;
while((line = buff.readLine()) != null)
{
Toast.makeText(this, line, Toast.LENGTH_LONG).show();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Does anyone know why I am getting the FileNotFoundException?
Is it a path issue?
Don't really know how is built your application, but, the error you get does seem like a path issue, are you sure both Activities are in the same folder ?
If not, you'll need to set either an abolute path (like : "/home/user/text.txt") for the text file or a relative path (like : "../text.txt").
If you're not sure, try to print the current path for the Activity using some command like
new File(".").getAbsolutePath();
And, although I can't say I'm expert with Android, are you sure you need the Context.MODE_WORLD_WRITEABLE for your file ? If no other application than yours is reading or writing from/to it, it should not be necessary, right ?
it is surealy a path issue.
you can write like this
fpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory";
File custdir=new File(fpath);
if(!custdir.exists())
{
custdir.mkdirs();
}
File savedir=new File(custdir.getAbsolutePath());
File file = new File(savedir, filename);
if(file.exists())
{
file.delete();
}
FileOutputStream fos;
byte[] data = texttosave.getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
Toast.makeText(getBaseContext(), "File Saved", Toast.LENGTH_LONG).show();
finish();
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(), "Error File Not Found", Toast.LENGTH_LONG).show();
Log.e("fnf", ""+e.getMessage());
// handle exception
} catch (IOException e) {
// handle exception
Toast.makeText(getBaseContext(), "Error IO Exception", Toast.LENGTH_LONG).show();
}
and you can read like
String locatefile=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory"+"/filename";
try {
br=new BufferedReader(new FileReader(locatefile));
while((text=br.readLine())!=null)
{
body.append(text);
body.append("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have trouble with saving images on sd card. I can see the file on the sd card but file is empty (size 0). I tried saving it on the phone memory and it works fine. Here is my code.
Imagewritter {
public static boolean writeAsJPG(Context context, Bitmap bitmap,
String filename) {
filename = filename + ".jpg";
File path = Environment.getExternalStorageDirectory();
File f = new File(path, filename);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "file not found");
return false;
}
bitmap.compress(CompressFormat.JPEG, quality, fos);
try {
fos.flush();
fos.close();
} catch (IOException e) {
Log.d(TAG, "error closing");
e.printStackTrace();
}
}
here is the code where the bitmap comes from.
DrawingView = (drawing) findViewById(R.id.drawing_view);
drawingBitmap = (Bitmap) DrawingView.getBitmap();
String idName = timeStampText;
//save Image as JPG
ImageWritter.writeAsJPG(getApplicationContext(), drawingBitmap, idName);
i think u have to add these permission in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Get the image in byte array & check the size of that byte array.. I think you getting 0 size byte array.....
The only problem here is that I have two lines for writing the file. Using FileOutputStream and OpenFileOutput. Just remove these lines and it'll be fine.
try {
fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "file not found");
return false;
}