Writing to text file in "APPEND mode" in emulator-mode, - android

In my Android app I should store the data from user in simple text-file, that I created in the raw directory. After this, I'm trying to write file in APPEND MODE by using simple code from the Google's examples:
try
{
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_APPEND);
fos.write((nameArticle+"|"+indexArticle).getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
But nothing happens: no exceptions, but I can see nothing in my FILE_NAME, besides the single record, which was added by me.
What am I doing wrong ? Is it possible at common to write to file in emulator ?

openFileOutput will only allow you to open a private file associated with this Context's application package for writing. I'm not sure where the file you're trying to write to is located. I mean full path. You can use the code below to write to a file located anywhere (as long as you have perms). The example is using the external storage, but you should be able to modify it to write anywhere:
public Uri writeToExternalStoragePublic() {
final String filename = mToolbar.GetTitle() + ".html";
final String packageName = this.getPackageName();
final String folderpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName + "/files/";
File folder = new File(folderpath);
File file = null;
FileOutputStream fOut = null;
try {
try {
if (folder != null) {
boolean exists = folder.exists();
if (!exists)
folder.mkdirs();
file = new File(folder.toString(), filename);
if (file != null) {
fOut = new FileOutputStream(file, false);
if (fOut != null) {
fOut.write(mCurrentReportHtml.getBytes());
}
}
}
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
return Uri.fromFile(file);
} finally {
if (fOut != null) {
try {
fOut.flush();
fOut.close();
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
In the example you have given, try catching 'I0Exception`, I have a feeling you do not have permission where you are trying to write.
Have a Happy New Year.

Related

Android Studio : How to save text files from EditText into a specific directory

I am currently making a journal app, so the users type their entry into an EditText and it saves in their phone and they can load it up later. At first I used just getFilesDir() but recently there is this weird rList file that shows up every time I open the app and I couldn't figure it out(I wrote a question about it). So now I want to save these files in this specific directory called TextEntries
Here is the code for my save funcction:
public void save(View v) {
textFile = inputTitle.getText().toString();
String text = inputFeelings.getText().toString();
FileOutputStream fos = null;
try {
String rootPath = getFilesDir().getAbsolutePath() + "/TextEntries/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
fos = openFileOutput(textFile, MODE_PRIVATE);
fos.write(text.getBytes());
inputFeelings.getText().clear();
Toast.makeText(this, "Saved to " + getFilesDir() + "/TextEntries/" + textFile,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
All help is welcome and thank you in advance.
replace
openFileOutput(textFile, MODE_PRIVATE);
with
new FileOutputStream(rootPath + textFile)

Why can't I save file in external storage or memory card?

I would like to create a backup file in my memory card but all it does is return a file not found exception. I am specifying the path where the data should be saved. When i choose the Internal storage the file was saved but when i changed it to external storage, it returns me the file not found.
Here are the Screenshots:
enter image description here
final Preference prefStoragePath = findPreference("key_storage_path");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String pref_storage_path = settings.getString("set_storage_path",null);
startingDir = (pref_storage_path!=null)? pref_storage_path : Environment.getExternalStorageDirectory().toString();
Preference prefBackupManual = findPreference("key_backup_manual");
final String root = Environment.getExternalStorageDirectory().toString();
prefBackupManual.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
createBackupData(startingDir);
return false;
}
});
private void createBackupData(String dir){
String filename = "BackupData.txt";
String data = resultSet().toString();
try{
byte[] sha1hash;
File myFile = new File(dir,filename);
sha1hash = data.getBytes("UTF-8");
String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
FileOutputStream fos = new FileOutputStream(myFile);
fos.write(base64.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
}finally {
Toast.makeText(getActivity(),"File saved in " + dir + "/" + filename ,Toast.LENGTH_SHORT).show();
}
}
what is happening?
you are trying to write data into a file that does not exist, thus a FileNotFoundException is thrown. The File(String, String) constructor does not create an actual file, you must take care of that by yourself.
How to fix it?
Check that your app has declared <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in the Manifest. If you are targeting SDK 23 or above you should check and request that permission at runtime.
Your save method should look like:
private void createBackupData(String dir) {
String filename = "BackupData.txt";
String data = resultSet().toString();
FileOutputStream fos = null;
try {
byte[] sha1hash;
File myFile = new File(dir, filename);
//NOTE: your file will be overwritten in case it already exists
if (myFile.exists() || myFile.createNewFile()) {
sha1hash = data.getBytes("UTF-8");
String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
fos = new FileOutputStream(myFile);
fos.write(base64.getBytes());
Toast.makeText(getActivity(), "File saved in " + dir + File.separator + filename, Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
} finally {
if (fos != null)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: a better approach is using Environment.getExternalStorageDirectory().getAbsolutePath() instead of Environment.getExternalStorageDirectory().toString()

Able to Receive file but file not storing in Android External Storage

I am creating Xmpp application using SMACK api and Spark for test.
I am able to send from Spark but I cannot see Any Directory and File created in android gallery.
I log the method incoming.getAmountWritten() and it is giving me
07-27 21:00:58.789: V/Receiving Status ...(17652): 208861
It means I have got the file and now I have to write on physical storage. May be there is problem with my android code.
Please find Android Code
#Override
public void fileTransferRequest(final FileTransferRequest fileRequest) {
final File dir = Environment.getExternalStorageDirectory();
final File folder = new File(dir+ "/illuxplain/");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Thread receiving = new Thread(new Runnable() {
#Override
public void run() {
IncomingFileTransfer incoming = fileRequest.accept();
Log.v("Receiving File Name", incoming.getFileName());
File file = new File(folder, incoming.getFileName());
try {
incoming.recieveFile(file);
while (!incoming.isDone()) {
try {
Thread.sleep(1000L);
} catch (Exception e) {
Log.e("", e.getMessage());
}
if (incoming.getStatus().equals(Status.error)) {
Log.e("ERROR!!! ", incoming.getError() + "");
}
if (incoming.getException() != null) {
incoming.getException().printStackTrace();
}
}
Log.v("Receiving Status ... ",""+incoming.getAmountWritten());
} catch (Exception e) {
e.printStackTrace();
Log.e("", e.getMessage());
}
}
});
receiving.start();
}else{
System.out.println("Directory Not Created");
}
}
}
When I go to gallery and see if I got the file. I see no directory created and of course no file.
You need to write the data into the file. Here is an example to code to write the data in to the file
File file = new File(folder, incoming.getFileName());
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(file);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

Copying file from asset folder to sdcard doesn't seem to work

I am trying to copy an image from the asset folder to the sdcard but doesn't seem to copy it on first launch. It creates the folder okay but doesn't copy the file over.
prefs = getPreferences(Context.MODE_PRIVATE);
if (prefs.getBoolean("firstLaunch", true)) {
prefs.edit().putBoolean("firstLaunch", false).commit();
File nfile=new File(Environment.getExternalStorageDirectory()+"/My Images");
nfile.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("middle.jpg");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images" + filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
}
middle.jpg is the file i want to copy over. Can any one tell me what i am doing wrong?
PS i have WRITE_EXTERNAL_STORAGE in my manifest.
Thanks
You forgot to add / in the end of /My images while constructing the path
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images/" + filename);
out = new FileOutputStream(outFile);
because the filename would be MyImages+Filename so it wouldn't exists for copying.

I can create file but can't write to it

Could someone look at this snippet of code please and let me know what I'm doing wrong? It's a simple function that takes a string as parameter which it uses as a file name, adding ".txt" to the end of it.
The function checks if the file exists, creating it if it doesn't and then writes two lines of text to the file. Everything appears to be working and the file is created successfully on the sd card. However, after everything is done, the file is empty (and has a size of 0 bytes).
I suspect it's something obvious that I'm overlooking.
public void writeFile(String fileName) {
String myPath = new File(Environment.getExternalStorageDirectory(), "SubFolderName");
myPath.mkdirs();
File file = new File(myPath, fileName+".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
Toast.makeText(this, "Error Creating File", Toast.LENGTH_LONG).show();
return;
}
}
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
// Do whatever
}
}
Hi I will show you the full code I use, works perfect.
I don't use
new OutputStreamWriter()
i use
new BufferedWriter()
here is my Snippet
public void writeToFile(Context context, String fileName, String data) {
Writer mwriter;
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + "myFolder");
if (!dir.isDirectory()) {
dir.mkdir();
}
try {
if (!dir.isDirectory()) {
throw new IOException(
"Unable to create directory myFolder. SD card mounted?");
}
File outputFile = new File(dir, fileName);
mwriter = new BufferedWriter(new FileWriter(outputFile));
mwriter.write(data); // DATA WRITE TO FILE
Toast.makeText(context.getApplicationContext(),
"successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
mwriter.close();
} catch (IOException e) {
Log.w("write log", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external storage.",Toast.LENGTH_LONG).show();
}
}
-- Original Code --
That one took a while to find out. The javadocs
here brought me on the right track.
It says:
Parameters
name The name of the file to open; can not contain path separators.
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_APPEND to append to an existing file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
The file is created, if it does not exist, but it is created in the private app space. You create the file somewhere on the sd card using File.createNewFile() but when you do context.openFileOutput() it creates always a private file in the private App space.
EDIT: Here's my code. I've expanded your method by writing and reading the lines and print what I got to logcat.
<pre>
public void writeFile(String fileName) {
try {
OutputStreamWriter writer = new OutputStreamWriter(
getContext().openFileOutput(fileName + ".txt", Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
// Now read the file
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(
getContext().openFileInput(fileName + ".txt")));
for(String line = is.readLine(); line != null; line = is.readLine())
Log.d("STACKOVERFLOW", line);
is.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
}
Change the mode from Context.MODE_PRIVATE to Context.MODE_APPEND in openFileOutput()
MODE_APPEND
MODE_PRIVATE
Instead of
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
Use
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_APPEND));
UPDATE :
1.
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
OutputStreamWriter writer = new OutputStreamWriter(osr);
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write("First line");
fbw.newLine();
fbw.write("Second line");
fbw.newLine();
fbw.close();
Or 2.
private void writeFileToInternalStorage() {
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
String eol = System.getProperty("line.separator");
BufferedWriter fbw = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(osr);
fbw = new BufferedWriter(writer);
fbw.write("First line" + eol);
fbw.write("Second line" + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fbw != null) {
try {
fbw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Categories

Resources