I have my android activity :
try {
File root=Environment.getExternalStorageDirectory();
Log.i("root",root.toString());
File dir=new File(root.getAbsolutePath() + "/downloads");
dir.mkdirs();
file=new File(dir,"mytext.txt");
FileOutputStream out=new FileOutputStream(file,true);
PrintWriter pw=new PrintWriter(out);
pw.println("Hello! Welcome");
pw.println("You are Here...!!!");
pw.flush();
pw.close();
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
also added :
<uses-permission android:name="androd.permission.WRITE_EXTERNAL_STORAGE"/>
but it throws me FileNotfound exception :
01-13 09:06:44.442: WARN/System.err(419): java.io.FileNotFoundException: /mnt/sdcard/downloads/mytext.txt (No such file or directory)
and if i add
if(file.exists()){
System.out.println("file exists");
}
else{
System.out.println("No such Fileeeeeeeeee");
}
it moves into "else" part.
Thanks
Sneha
Try this,,it works for me
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
//now attach OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
GO through this for more details
In Android 6 (Marshmallow) I had to explicitely check whether my app has permission "WRITE_EXTERNAL_STORAGE"
Not sure but please verify that there exists External Storage in your emulator or phone otherwise it will through exception.
Related
I am trying to save data into text file in the internal storage and read it again .. It works fine in my mobile with android 11 but when i tried at android 8 it gives me this error
java.io.FileNotFoundException:/data/user/0/com.example.example/test.txt
(No such file or directory)
It appears at the first time to open the activity but i can clear it - as normal text - and write a new text and save it so the file is there and usable
here is read code
File path = getApplicationContext().getFilesDir();
File readFrom = new File(path, fileName);
byte[] content = new byte[(int) readFrom.length()];
try {
FileInputStream stream = new FileInputStream(readFrom);
stream.read(content);
return new String(content);
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
and this write code
public void writeToFile(String fileName, String content) {
File path = getApplicationContext().getFilesDir();
try {
FileOutputStream writer = new FileOutputStream(new File(path, fileName));
writer.write(content.getBytes());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Here's my code:
String content = mEditText.getText().toString();
FileOutputStream fos;
try {
fos = openFileOutput(title, MODE_PRIVATE);
fos.write(content.getBytes());
Toast.makeText(EditActivity.this, "Saved to "+getFilesDir() + "/" + title, Toast.LENGTH_LONG).show();
fos.close();
saved = true;
} catch (IOException e) {
Toast.makeText(EditActivity.this, "Error happened", Toast.LENGTH_SHORT).show();
}
If I run the code like this, it tells saved to /data/data/mypackagename/files/FileTitle. I want it to save the file in another directory for example save to /data/data/mypackagename/files/userData/FileTitle.I don't know any way to do this
What you need is the File constuctor that takes a parent File and a relative path to file. You've correctly established that openFileOutput() creates the file in getFilesDir(), so the code would look something like this:
FileOutputStream fos = null;
try {
final File dir = new File(getFilesDir(), "some/long/path");
dir.mkdirs();
final File file = new File(dir, "file.txt");
fos = new FileOutputStream(file);
// Use fos...
} catch (IOException e) {
// Handle error...
} finally {
if (fos != null) {
try {
fos.close()
} catch (IOException ignore) {
// Close quietly.
}
}
}
File is just a pointer, it may point to a directory, it may even point to something that's not there yet, like a new file. FileOutputStream will create a file if it doesn't exist.
If you choose to place your new file in another directory, make sure it exists first by calling mkdirs() on the directory.
I want to create a folder and put all generated file in this folder so I have created this method to create a directory in external storage named MyAppFolder and put a .nomedia file in this folder to avoid media indexing
static String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
static String baseAppDir = "MyAppFolder";
static String fileHider = ".nomedia";
public static void createFolder() {
try {
File mainDirectory = new File(baseDir + File.separator + baseAppDir);
if (!(mainDirectory.exists())) {
mainDirectory.mkdirs();
File outputFile = new File(mainDirectory, fileHider);
try {
FileOutputStream fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} catch (Exception exc) {
System.out.println("ERROR: " + exc.toString());
exc.printStackTrace();
}
}
I'm testing this on emulator but doesn't work, and I cannot understand how should I fix it.
The error log is:
java.io.FileNotFoundException: /storage/sdcard/MyAppFolder/.nomedia: open failed: ENOENT (No such file or directory)
02-12 20:11:51.758 4899-4899/com.myapp.testapp W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:409)
at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
02-12 20:11:51.758 4899-4899/com.myapp.testapp W/System.err﹕ at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
02-12 20:11:51.758 4899-4899/com.myapp.testapp W/System.err﹕ at com.myapp.testapp.MyFileManager.createFolder(MyFileManager.java:272)
I have also tried with
File outputFile = new File(mainDirectory, fileHider);
if(!outputFile.exists()) {
outputFile.createNewFile();
}
try {
FileOutputStream fos = new FileOutputStream(outputFile, false);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
same result
Make sure you have the permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Your code can work on my device. If you do have the permission, due to some tiny differences between our Android systems, you can try to create a hidden directory, and create a file inside of it.
static String baseAppDir = ".MyAppFolder";
static String fileHider = "nomedia";
Type in "ls -a" to check whether the hidden file has been really created. Don't 100% trust the exception log sometimes.
From Java FileOutputStream Create File if not exists says you should do the following. It does state that FileOutputStream should be able to create if it doesn't exist but will throw exception if it fails so it's better to do the following. I guess this is a more sure-fire way it will work? I dunno. Give it a shot! :-)
File yourFile = new File("score.txt");
if(!yourFile.exists()) {
yourFile.createNewFile();
}
FileOutputStream oFile = new FileOutputStream(yourFile, false);
I am trying to retrieve a file via FTP but I am getting the following error in LogCat:
java.io.FileNotFoundException :/config.txt (read-only file system)
I have verified that the file exists on the server, and I can read it by double clicking it in a web browser.
Can anyone help please? Here is the code I am using:
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("xxx.xxx.xxx.xxx");
client.enterLocalPassiveMode();
client.login("user", "pass");
//
// The remote file to be downloaded.
//
String filename = "config.txt";
fos = new FileOutputStream(filename);
//
// Download file from FTP server
//
client.retrieveFile("/" + filename, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
You cannot save files on the root of the phone. Use Environment.getExternalStorageDirectory()to get an file object of the SD card's directory and save the file there. Maybe create a directory for it. To do that you need the permission android.permission.WRITE_EXTERNAL_STORAGE.
Sample code:
try {
File external = Environment.getExternalStorageDirectory();
String pathTofile = external.getAbsolutePath() + "/config.txt";
FileOutputStream file = new FileOutputStream(pathTofile);
} catch (Exception e) {
e.printStackTrace();
}
You are trying to read the file in, but you have created an OutputStream, you need to create an inputStream and then read the file from that input stream.
Here is a great article, with come code that is very helpful. This should get you headed in the right direction.
http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
I hope this helps!
Best of luck
I have a set of image urls. I download it to bitmap. Now I want to store these images into sdcard/project folder. If I don't have such a file, I have to create it. What I have done right now is:
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, imageName);
if(!file.exists()) {
file.mkdir();
try {
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(), "file://"
+ file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
But I am not getting images inserted into sdcard. What is wrong in my code? Please reply. Thanks in advance.
Try using the below code:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
String fileName = edtNameImage.getText().toString().trim();//this can be changed
if (fileName.equalsIgnoreCase("")) {
Toast.makeText(context, "Fields cannot be left blank",
Toast.LENGTH_SHORT).show();
return false;
}
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + fileName);
// write the bytes in file
FileOutputStream fo;
try {
file.createNewFile();
fo = new FileOutputStream(file);//snapshot image is the image to be stored.
if (snapShotImage!=null)
{
snapShotImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
}else{
return false;
}
fo.write(bytes.toByteArray());
// ChartConstants.IMAGE_STORAGE++;
fo.flush();
fo.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return true;
You can also check for duplicacy in names with some additional code lines.
Let me know if it helps.
Have you made sure that the appropriate permissions for writing to/reading from an external storage device have been set in your Manifest.xml file?
Also, does the code exit with any of the exceptions above? Print more illustrative messages than the stacktrace. Something like so:
try {
} catch (FileNotFoundException e) {
Log.v(this.toString(), "Exception caught in block");
}
or something on these lines..
HTH
Sriram
Problems with your code:
1) You are creating a directory with the filename. Instead try mkdir() with only the 'path'
2) Pass only 'file.getAbsolutePath()' without the "file://" to insertImage() function
3) There is an alternate api to insertImage for which you need not create one more file locally. Pass the bitmap directly to that.
Hope this helps.