I am a beginner when it comes to Android. I encountered a problem, regarding writing to a file. I want to save to a file the input I get in a form. However, the piece of code that I wrote is not writing in my file. Could anyone please help me?
The code looks like that:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder s = new StringBuilder();
s.append("Event name: " + editText1.getText() + "|");
s.append("Date: " + editText2.getText() + "|");
s.append("Details: " + editText3.getText() + "|");
File file = new File("D:\\config.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024);
out.write(s.toString());
out.newLine();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
So, I have a form containing 3 fields: the name of an event, the date and the description. These I want to save to my file. I should mention that I use an emulator for testing.
Use following path for file. It will write file to your root folder of storage.
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");
writeToFile("File content".getBytes(), file);
writeToFile
public static void writeToFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
Don't forget to add following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
https://github.com/rznazn/GPS-Data-Logger/blob/master/app/src/main/java/com/example/android/gpsdatalogger/StorageManager.java
Here is a... nearly complete class for writing to the documents folder on the emulated external storage of the device.
Don't forget to add the write permissions to manifest.
Related
I'm developing an app in which I'm sending a .txt file from one end by attaching it with gmail. Everytime this file is sent, its name is data.txt. When this file is downloaded at the other end, on the first download its name is the same, i.e. data.txt. However, when another file is sent with the same name, the name of the file at the receiveing end becomes data-1.txt, data-2.txt etc. And because of this, I'm not able to read the proper file. Please could someone give me some suggestions to solve this problem? The sending and receiving code is given below: SEND
bSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
String toWrite = enterText.getText().toString();
FileOutputStream fos;
try {
String path = Environment.getExternalStorageDirectory().toString();
Log.v("path", path);
File myFile = new File("" + path + "/" + fileName + ".txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(toWrite);
Log.v("file written", toWrite);
myOutWriter.close();
fOut.close();
Uri u1 = null;
u1 = Uri.fromFile(myFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "MPPT Configuration Data");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
READ:
bRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/storage/sdcard0/download/" + fileName + ".txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
Log.v("read data", "" + aBuffer);
tvData.setText(aBuffer);
}catch (IOException e2) {
e2.printStackTrace();
}
}
});
I found a possible solution. I can link the file manager (external app) from where the user can pick out whichever file he wants to be read.
Thanks #greenapps fir the idea of displaying a list of files.
You can get all the file by using regex ,then process the file by following way:
1.if only one file found,read it;
2.if more than one file found, compare and read the file which last number is biggest
but this solution still has one problem,if has file data.txt and data-3.txt ,the file we want to read may become data-2.txt,but what we really read is data-3.txt.
Or,maybe you can get the file you want by judging file established time.
My device is htc one dual sim and for some reason Environment.getExternalStorageDirectory() is my memory of the phone, it's not removable sd card.
I tried to find the real sd card path using this:
public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
And i got
/mnt/media_rw/ext_sd
I tried to write files to /mnt/media_rw/ext_sd/downloads
but the file didn't appear to be created.
File file = new File("/mnt/media_rw/ext_sd/downloads", "test.txt");
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("sdfsdfsfd");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
02-11 23:12:35.236 9110-9110/www.jenyakirmiza.com.testsdcard W/System.errīš java.io.FileNotFoundException: /mnt/media_rw/ext_sd/downloads/test.txt: open failed: EACCES (Permission denied)
I heard smth about restriction starting from 4.4 so now we can't write files to removable sd card. But they said you can write filed to /sdcardpath/Android/data/your.package.name
ps. of course i added write_external permisssion to manifest.
You can find all external storages with Context.getExternalMediaDirs and can check whether it is removable with Environment.isExternalStorageRemovable(File). Note that Downloads directory will most likely be only in the primary (emulated) external storage.
Try using Environment.getExternalStorageDirectory() method :
File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "test.txt");
and you can evaluate first if your file really exists with exists() method :
File file = new File(Environment.getExternalStorageDirectory() + "/Download/", "test.txt");
if(file.exists()){
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("sdfsdfsfd");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Very important to have this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
inside your
AndroidManifest.xml
i try to write text in file.i wrote code ,witch can to write text ,but if i will use again my code again text is rewrite in file.for example if i first time write "Hello android" and then "Sir",result is only "Sir".i want "Hello android Sir"
your_file = new File("/sdcard/facebookUser");
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(
your_file), "UTF-8");
writer.write(facebook_user_name + ",");
writer.write(facebook_id);
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
how i can write code to save another text in this file second time?
new FileOutputStream(your_file, true)
public FileOutputStream(String name, boolean append) throws FileNotFoundException
append - if true, then bytes will be written to the end of the file rather than the beginning
Instead of:
writer = new OutputStreamWriter(new FileOutputStream(
your_file), "UTF-8");
Use:
writer = new OutputStreamWriter(new FileOutputStream(
your_file, true), "UTF-8");
This sets the FileOutputStream in append mode.
java.io.FileOutputStream.FileOutputStream(File file, boolean append)
throws FileNotFoundException
Constructs a new FileOutputStream that writes to file. If append is
true and the file already exists, it will be appended to; otherwise it
will be truncated. The file will be created if it does not exist.
try {
int n = 0;
String Name = "file";
File myFile = new File("/sdcard/test/");
if (!myFile.exists()) {
boolean b = myFile.mkdirs(); }
myFile = new File("/sdcard/test/"+Name+".txt");
while (myFile.exists())
{
myFile = new File("/sdcard/test/"+Name+n+".txt");
n++;
}
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
String str = "Your text to write";
myOutWriter.append(str);
myOutWriter.close();
fOut.close();
} catch (Exception e) {}
And do not forget permision:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Vladimir Kulyk and user2450263 are correct! You have to write a file in append mode. try this link.
I am trying to open the sdcard's .txt file in my EditText to change the text in it and
save the changes using button click but its not going in right way .May I know what is the correct way to achieve my objective?
try this one..
you must set permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "followed by ur file dir");
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "sdcard.txt");
for (File wavfile : f.listFiles())
{
String str = wavfile.getName().toString();
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/sdcard/"+filename);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
edtitext.setText(aBuffer.tostring());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext
(),aBuffer,Toast.LENGTH_LONG).show();
}
}
again btnclick you have to write that edited string right..
use this one for write in that file..
FileOutputStream fos;
try {
File myFile = new File("/sdcard/"+sdcard.txt);
myFile.createNewFile();
FileOutputStream fOut = new
FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new
OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(),filename + "
saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
thank you...
more detalis ref this link'
http://www.javatpoint.com/android-external-storage-example
----------------------------------------------------------
Some manufacturers (mainly Samsung) give write permissions only to the internal storage mounted at /storage/sdcard.
Also you should enable your app to write to external storage by adding this permission in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
First try to read the complete text file and save the text in a string.
For that you can refer this link
When you read the complete text file and get the text in a string, set the string to the editText by
edtitext.setText(your string);
I am working on a method that writes an XML file to the device. I've allowed external storage in the manifest file, but I can't find the file at the location it should be.
Here is my code:
public static void write (){
Serializer serial = new Persister();
File sdcardFile = new File("/Prueba/file.xml");
Item respuestas = new Item();
try {
serial.write(respuestas, sdcardFile);
} catch (Exception e) {
// There is the possibility of error for a number of reasons. Handle this appropriately in your code
e.printStackTrace();
}
Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());
}
}
Sdcard File path problem. Here is an exaple that write string in file.xml file.
File myFile = new File("/sdcard/file.xml");
try {
File myFile = new File("/sdcard/file.xml");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("encodedString");
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
You able to get External Storage name by this way,
String root = Environment.getExternalStorageDirectory().toString();