Android save text file - android

The question is pretty common and I have googled it a few but I still have problems. I have to save in a text file some data for a game that I am trying to develop. This is the code:
if (!isSecond(game[k])) {
//Where I'd like to save the file
File myFile = new File(Environment.getExternalStorageDirectory() + "/flagQuiz/record.txt");
//Try to save my file
try {
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
//correctGuess and TimeElapsed are two integers
myOutWriter.append(String.valueOf(correctGuess) + "-" + String.valueOf(TimeElapsed));
myOutWriter.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The log cat shows me this kind of error:
I have declared the possibility to save stuff in the SD Card in this way I guess:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Where is the mistake? flagQuiz folder is already created at runtime.

Be sure to check if file.exists() if true then delete it and create new one
else false then just carry on with your try block

Related

java.io.fileNotFoundException(Permission denied)

I have the next method :
public void saveOnSDCard() {
File path = new File("storage/sdcard1");
File dir = new File(path + "");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "test.png");
OutputStream os;
try {
os = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
} catch (IOException ioe) {
showToast("Ошибка " + ioe.toString());
}
}
but when i try to call it, it gives me a java.io.fileNotFoundException(Permission denied).
I have the next permission in my Manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
So can someone tell me what's wrong ?
P.S image - Bitmap object, i declared it in another method.
try if one of the following solutions works:
replace "storage/sdcard1" with"storage/sdcard1/"
replace path + "" with path + "/"
replace "test.png" with "/test.png"
I think it's just missing a slash in one of those three lines
Guy in comment told me that if you have an android 4.4+ you can write to sdcard only when you make your sdcard as primary memory or sometimes when ur phone is rooted. I tried it and it really works.

Android Append text to file not working even if fileOutputStream appending mode setted to TRUE

I am trying to append text into a file stored in emulated/0/.. folder (external storage without SD Card)
FileOutputStream fileOutputStream = new FileOutputStream(capturesFile, true);
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
String data = "my data";
writer.append(data);
writer.close();
fileOutputStream.flush();
fileOutputStream.close();
This code is not working, I really do not understand why. Is the emulated location is a problem (stupid question but at this point...) I already tried many ways without any positive solution.
Is someone have an idea about this issue.
Use this code
try {
FileWriter fw = new FileWriter("path/of/file",true);
fw.write("myData");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
First make sure you've given the required permission to write a file and that would be -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in Manifest file and
if (ContextCompat.checkSelfPermission(context,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_EXT_STORAGE);
}
in your activity.
Second please check your directory path. There might be some chances that you are using a wrong path. Easiest way to get a direct path for the Internal Storage is -
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data" + getApplicationContext().getPackageName();
File file = new File(path + "/File.txt");
You can use this method as per your requirement to write a file -
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.append("My Data");
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

No such file or directory when trying to save file

For an App I am developing, I want to write some text to a text file on the SD card. I've tried to do that with the code below. This gives an error but I can't see why. As far as I can tell I have followed all the examples on the web perfectly. In logcat I see the first log, but not the second one so the problem is in the creation of the file. Do you guys have an idea what's going wrong?
public void saveDataToFile(String data, String fileName) {
Log.d("Checks", "Trying to save data");
try {
// Set up the file directory
String filePath = Environment.getExternalStorageDirectory().toString() + "/Data Folder";
File fileDirectory = new File(filePath);
fileDirectory.mkdirs();
Log.d("Checks", "Directory created");
// Set up the file itself
File textFile = new File(fileDirectory, fileName);
textFile.createNewFile();
Log.d("Checks", "File created");
// Write to the file
FileOutputStream fileOutputStream = new FileOutputStream(textFile);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.append(data);
outputStreamWriter.close();
fileOutputStream.close();
Toast.makeText(mContext, "Done writing to SD card", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
EDIT:
Turns out I had forgotten to add the right permission to the manifest. It works now!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Did you declare the proper uses permissions to access and write to the External SD card ?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android does not make director(mkdir)

SOLVED
i change it a litle bit
File path = new File(Environment.getExternalStorageDirectory(), "AndroidPaint");
File file = new File(path, tmpImg);
path.mkdirs();
if(!file.exists()) {
file.createNewFile();
}
os = new FileOutputStream(file);
source.compress(CompressFormat.JPEG, 100, os);
os.flush();
os.close();
also problem could be source Bitmap i discovered then was null
PROBLEM
on my Android program i want save bitmap on external store i got permission for do that
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
and got some code for that
public class SaveOpen {
public static void save(Bitmap source) {
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".jpg";
OutputStream os = null;
try {
File dir = new File(Environment.getExternalStorageDirectory(), "myapp");
if (!dir.mkdirs()) {
Log.e("save", "Directory not created");
}
File file = new File(dir, tmpImg);
if(!file.exists()) {
file.createNewFile();
}
os = new FileOutputStream(file);
source.compress(CompressFormat.JPEG, 100, os);
os.flush();
os.close();
}
catch (IOException e) {
Log.d("save", e.getMessage());
}
}
}
but when i press save button on my app i get
open failed: ENOTDIR (Not a directory)
exception, what i do wrong.? i tried all guide i found in google, pls help
try this:
String myDir = Environment.getExternalStorageDirectory() + "/myapp";
File dir = new File(myDir);
On older devices access to external storge is not possible if there's is USB connection (disk mode), so log what is Environment.getExternalStorageDirectory() returning in your case.
I met the same problem, it seems like a bug on Android, I mkdir in the command line by adb, also failed. Then I try to restart the phone, never happen again.
My problem solved by add permissions to access external storage:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

android error trying to write to external SD

I am trying to write a jpg image to the external SD card. However, I am getting System.err FileNotFoundException: /mnt/sdcard/test.images/temp/savedImage (no such file or directory). Creating the directory also seems to fail and gives a false in LogCat and I also cannot see the folder when looking on my SD card.
My code is as follows:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File folder = new File(Environment.getExternalStorageDirectory() + "/test.images/temp");
try {
if(!folder.exists()){
boolean dir = new File(Environment.getExternalStorageDirectory() + "/test.images/temp").mkdir();
Log.v("creating directory", Boolean.toString(dir));
}
File imageOutputFile = new File(Environment.getExternalStorageDirectory() + "/test.images/temp", "savedImage");
FileOutputStream fos = new FileOutputStream(imageOutputFile);
Image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I have permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
in the manifest and have cleaned and rebuilt.
Use mkdirs() instead of mkdir().
Guido posted a solution that works for me in the comment. I am going to repeat it just to make sure it can be an answer.

Categories

Resources