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);
Related
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.
Within my app I am trying to write a file, which I can then internally read from.
Would anyone have an example of how to write files to the installation folders of app?
use the following code to write from Edittext into file and read from file into Edittext
set the following permission to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
JAVA CODE
EditText LoadedText;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadedText=(EditText) findViewById(R.id.LoadedText);
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File("/sdcard/RouterSetup.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
LoadedText.setText(text.toString());
}
public void saveFile() {
try {
File myFile = new File("/sdcard/RouterSetup.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(LoadedText.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD " + LoadedText.getText() + ".txt",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
getFilesDir() vs Environment.getDataDirectory()
public File getFilesDir ()
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
public static File getExternalStorageDirectory ()
Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().
If you want to get your application path use getFilesDir() which will give you path /data/data/your package/files
You can get the path using the Environment var of your data/package using the
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath(); which will return the path from the root directory of your external storage as /storage/sdcard/Android/data/your pacakge/files/data
To access the external resources you have to provide the permission of WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
The simplest solution is
String filename = "stuff.xml";
READ
FileInputStream stream = ctx.openFileInput(filename);
(and below is a really simple example of parsing that file)
BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = buffReader.readLine()) != null) {
...
// do something cool
...
}
} catch (IOException e) {
Log.e("MyApp", "SCREAAAAAM", e);
}
WRITE
OutputStreamWriter outputStreamWriter = new OutputStreamWriter( ctx.openFileOutput(filename, Context.MODE_PRIVATE) );
outputStreamWriter.write("this is text not xml :(");
So the two main things to note are the openFileInput and openFileOutput methods of Context (ie your activity) which take care of the heavy lifting
//here i am downloading file from server and writing
String download_link = "some server location";
URL url = new URL(download_link);
HttpsURLConnection c = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
c = (HttpsURLConnection) url.openConnection();
c.setHostnameVerifier(DO_NOT_VERIFY);
}
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "Mobi.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
you need to add permission in manifest file:
uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
Which type of files you are talking about ?
For data storage you can use shared preferences.
For media type you can use media storage.
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.
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 using this code as a part to write data to a text file, but I am not sure how I can append the data to the new line. "\n" does not seem to be working. Here, variable "data" has this format:
t=1, x=-3.1, y=19.0, z=-8.6
this part of the code iterates and the variable "data" is written each time; the current result is something like:
t=1, x=-6.9, y=-9.6, z=-6.9t=2, x=-1.4, y=6.2, z=7.0t=3, x=-1.4, y=6.1, z=6.9t=4, and so on, but what I would like is:
t=1, x=-6.9, y=-9.6, z=-6.9
t=2, x=-1.4, y=6.2, z=7.0
t=3, x=-1.4, y=6.1, z=6.9
Thanks in advance for your help.
String datatest = data.toString();
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/test");
directory.mkdirs();
String filename = "test.txt";
File file = new File(directory, filename);
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(datatest + "\n");
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
try "\r\n"
and to make this answer longer :)