when using OutputStreamWriter, while I try to make multiple directories (depending on a function result) and writing strings into the files, I have an exception.
Why does my program keep jumping to exception and saveFile() always return false?
private boolean saveFile() {
File card = Environment.getExternalStorageDirectory();
File dir = new File(card.getAbsolutePath() + choosePath());
if (!dir.exists()) {
dir.mkdir();// creates directory by the given pathname
}
File file = new File(dir, etFileName.getText().toString());
try {
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(configString); // from character to byte
osw.flush();
osw.close();
return true;
} catch (IOException e) {
return false;
}
}
try this
private boolean saveFile() {
File card = Environment.getExternalStorageDirectory();
String fullPath = card.getAbsolutePath()
+ choosePath()
+ etFileName.getText().toString(); //I guess this should generate the fullPath, if i understood well your code
File file = new File(fullPath); //open the file
file.getParentFile().mkdirs(); //create parent dirs if necessary
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
try {
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(configString); // from character to byte
osw.flush();
osw.close();
return true;
} catch (IOException e) {
return false;
}
}
EDIT 1: added "file.createNewFile()"
EDIT 2: be sure to have the right to write file. You should have this in you manifest file
Related
I'm trying to save strings to a text file in the external memory of the android device.
I call this method:
public void writeToFile(String name, String mevent)
{
File path =
Environment.getExternalStoragePublicDirectory
(
Environment.DIRECTORY_DOWNLOADS
);
if(!path.exists())
{
path.mkdirs();
}
File myfile = new File(path, "config.txt");
try
{
myfile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myfile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(name);
myOutWriter.append(mevent);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
I call the above method from an OnActivityResult that waits for strings from another activity. The strings definitely return from the other activity, but the file isn't created. I have given the write permission to external memory.
Any ideas to what I am doing wrong?
I want to write something to a file. I found this code:
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The code seems very logical, but I can't find the config.txt file in my phone.
How can I retrieve that file which includes the string?
Not having specified a path, your file will be saved in your app space (/data/data/your.app.name/).
Therefore, you better save your file onto an external storage (which is not necessarily the SD card, it can be the default storage).
You might want to dig into the subject, by reading the official docs
In synthesis:
Add this permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It includes the READ permission, so no need to specify it too.
Save the file in a location you specify (this is taken from my live cod, so I'm sure it works):
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
Environment.DIRECTORY_DCIM + "/YourFolder/"
);
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
[EDIT] OK Try like this (different path - a folder on the external storage):
String path =
Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
// Create the folder.
File folder = new File(path);
folder.mkdirs();
// Create the file.
File file = new File(folder, "config.txt");
Write one text file simplified:
private void writeToFile(String content) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.append(content);
writer.flush();
writer.close();
} catch (IOException e) {
}
}
This Method takes File name & data String as Input and dumps them in a folder on SD card.
You can change Name of the folder if you want.
The return type is Boolean depending upon Success or failure of the FileOperation.
Important Note: Try to do it in Async Task as FIle IO make cause ANR on Main Thread.
public boolean writeToFile(String dataToWrite, String fileName) {
String directoryPath =
Environment.getExternalStorageDirectory()
+ File.separator
+ "LOGS"
+ File.separator;
Log.d(TAG, "Dumping " + fileName +" At : "+directoryPath);
// Create the fileDirectory.
File fileDirectory = new File(directoryPath);
// Make sure the directoryPath directory exists.
if (!fileDirectory.exists()) {
// Make it, if it doesn't exist
if (fileDirectory.mkdirs()) {
// Created DIR
Log.i(TAG, "Log Directory Created Trying to Dump Logs");
} else {
// FAILED
Log.e(TAG, "Error: Failed to Create Log Directory");
return false;
}
} else {
Log.i(TAG, "Log Directory Exist Trying to Dump Logs");
}
try {
// Create FIle Objec which I need to write
File fileToWrite = new File(directoryPath, fileName + ".txt");
// ry to create FIle on card
if (fileToWrite.createNewFile()) {
//Create a stream to file path
FileOutputStream outPutStream = new FileOutputStream(fileToWrite);
//Create Writer to write STream to file Path
OutputStreamWriter outPutStreamWriter = new OutputStreamWriter(outPutStream);
// Stream Byte Data to the file
outPutStreamWriter.append(dataToWrite);
//Close Writer
outPutStreamWriter.close();
//Clear Stream
outPutStream.flush();
//Terminate STream
outPutStream.close();
return true;
} else {
Log.e(TAG, "Error: Failed to Create Log File");
return false;
}
} catch (IOException e) {
Log.e("Exception", "Error: File write failed: " + e.toString());
e.fillInStackTrace();
return false;
}
}
You can write complete data in logData in File
The File will be create in Downlaods Directory
This is only for Api 28 and lower .
This will not work on Api 29 and higer
#TargetApi(Build.VERSION_CODES.P)
public static File createPrivateFile(String logData) {
String fileName = "/Abc.txt";
File directory = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/");
directory.mkdir();
File file = new File(directory + fileName);
FileOutputStream fos = null;
try {
if (file.exists()) {
file.delete();
}
file = new File(getAppDir() + fileName);
file.createNewFile();
fos = new FileOutputStream(file);
fos.write(logData.getBytes());
fos.flush();
fos.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I use the following code to write text content to MessageCleanupLogs.txt, it seems that it's a overwrite mode, when I run the code again, the previously created MessageCleanupLogs.txt is overwrite.
How can I set append mode for the file MessageCleanupLogs.txt to append new content? Thanks!
String filename=Environment.getExternalStorageDirectory() + "/MessageCleanupLogs.txt";
try
{
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
String aa="a\r\nb\r\nb";
FileOutputStream fOut = new FileOutputStream(filename);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("test");
myOutWriter.append("\r\n");
myOutWriter.append(aa);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
The java methods of append itself will work.
PrintWriter out = null;
String filepath = "/sdcard/myfile.txt"; // your file path here
String contents = "hello world"; // your file contents here
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(filepath, true)));
out.println(contents);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Reference from https://stackoverflow.com/a/1625263/3894784
I have been trying to save the file ( soundtrack ) from sdcard to the internal storage.
I have already done so with the image with this code
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/fairyTale/app_data/ImgMsc
File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,Name+".png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Now this works well, creates a directory and saves my bitmap, but i want to do the same thing for the music file.
Also i want to know how to read that file ( use it in the app ).
I have used this code to read the bitmap
File f=new File(path,name+".png");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
P.S. the code i have tried, but doesn't seem to be producing the right copy:
String filePath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+name;
File music = new File(filePath);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/fairyTale/app_data/ImgMsc
File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
File mypath=new File(directory,name+".mp3");
try {
InputStream is=new FileInputStream(music);
OutputStream os;
os = new FileOutputStream(mypath);
byte[] buff=new byte[1024];
int len;
while((len=is.read(buff))>0){
os.write(buff,0,len);
}
is.close();
os.close();
}
Here is the code that worked for me:
private void saveToInternalStorage(String name){
String filePath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+name;
File music = new File(filePath);
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to your data
File directory = cw.getDir("ImgMsc", Context.MODE_PRIVATE);
File mypath=new File(directory,name+".mp3");
// Create imageDir
try {
InputStream is=new FileInputStream(music);
OutputStream os;
os = new FileOutputStream(mypath);
byte[] buff=new byte[1024];
int len;
while((len=is.read(buff))>0){
os.write(buff,0,len);
}
is.close();
os.close();
DeleteFile(filePath);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Hope it helps!
With the following code, I try to write to my sdcard:
public void writedata(String data) {
//BufferedWriter out = null;
System.out.println(data);
try{
FileOutputStream out = new FileOutputStream(new File("/sdcard/tsxt.txt"));
out.write(data.getBytes());
out.close();
} catch (Exception e) { //fehlende Permission oder sd an pc gemountet}
System.out.println("CCCCCCCCCCCCCCCCCCCCCCCALSKDJLAK");
}
}
The permission in the Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
But now, when I open the file, nothing is in there. Where´s the problem? I´m sure data has some value.
EDIT:
I get this message in the LogCat:
02-06 01:59:51.676: W/System.err(1197): java.io.FileNotFoundException: /storage/sdcard0/sdcard/tsxt.txt: open failed: ENOENT (No such file or directory)
I tried to create the file on the sdcard but still the same error. Is there a code that the File is created if it doesn´t exists?
Try with this code:
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir");
File file = new File(dir, "tsxt.txt");
FileOutputStream f = new FileOutputStream(file);
So the path to the file is not correct. You should remove directory name:
File dir = new File (sdCard.getAbsolutePath() + "/");
Try this:
BufferedWriter out;
try {
FileWriter fileWriter= new FileWriter(Environment.getExternalStorageDirectory().getPath()+"/tsxt.txt")
out = new BufferedWriter(fileWriter);
out.write("Your text to write");
out.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
try{
File myFile = new File("/sdcard/tsxt.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("your data here");
myOutWriter.close();
fOut.close();
}catch(Exception e){}
Try this
FileOutputStream fOut =openFileOutput(Environment.getExternalStorageDirectory().getPath()+"/tsxt.txt",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//---write the string to the file---
osw.write(str);
osw.flush();
osw.close();
Before writing any file on sd card you need to check that is sdcard mounted or not, if not then just mount it and then write the file on it using external storage path.
you may use following code to check is sdcard mount or not
static public boolean hasStorage(boolean requireWriteAccess) {
//TODO: After fix the bug, add "if (VERBOSE)" before logging errors.
String state = Environment.getExternalStorageState();
Log.v(TAG, "storage state is " + state);
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (requireWriteAccess) {
boolean writable = checkFsWritable();
Log.v(TAG, "storage writable is " + writable);
return writable;
} else {
return true;
}
} else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
if(hasStorage(true)){
//call here your writedata() function
}
This Code is working perfectly..
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStorageDirectory() + "/files", albumName);
Log.d("File", "Bug file Created" + file.getAbsolutePath());
return file;
}`
To write the textfile inside sd Card(/storage/sdcard0/files/bugReport.txt)
try{
outputStream = new FileOutputStream(this.getAlbumStorageDir(bugReport.txt));
outputStream.write(report.toString().getBytes());
Log.d("File","Report Generated");
outputStream.close();
}
catch(Exception e){
e.printStackTrace();
}