I need to read a file in the sd card in my android device and write the contents of this file into another file in the sd card which is already existing.
Here is my code to read a file anywhere in the sdcard.
public String readFromFile(String fileName) {
String ret = "";
try {
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard, fileName);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
if ( bufferedReader != null ) {
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Can some one please tell me how can I copy the contents of this file into another file on sdcard after reading.
I do not wish to append but to overwrite the contents of the file.
I need a method in this format
void writeFile(String fileName, String Data){
//code to overwite with given data
}
Can someone please help me
Thanks in advance.
void writeFile(String fileName, String data) {
File outFile = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream out = new FileOutputStream(outFile, false);
byte[] contents = data.getBytes();
out.write(contents);
out.flush();
out.close();
}
The most important part is the false in the FileOutputStream constructor. The second parameter is append. If set to false, the file will be overwritten if it exists.
Related
Hi I have same problem by Writing String ArrayList to file and Reading.
This is my code for writing
File SettingsPath = getFilesDir();
String strSettingsPath = SettingsPath.toString() + "/settings.txt";
File file = new File (strSettingsPath);
if (!file.exists()) {
File removeFile = new File(strSettingsPath.toString());
boolean deleted = removeFile.delete();
}
try {
FileOutputStream fos =
new FileOutputStream(
new File(strSettingsPath));
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this.strSettings);
os.close();
Log.v("","File has been written");
} catch(Exception ex) {
ex.printStackTrace();
}
And this is for Reading
public void reader(View v) throws FileNotFoundException {
File SettingsPath = getFilesDir();
String strSettingsPath = SettingsPath.toString() + "/settings.txt";
List<String> Settings = new ArrayList<String>();
BufferedReader readerL = new BufferedReader(new FileReader(strSettingsPath));
String line;
try{
//line = readerL.readLine();
while ((line = readerL.readLine()) != null) {
Settings.add(line);
System.out.println("The Setting line is " + Settings);
}
readerL.close();
}catch (IOException e){
e.printStackTrace();
}
By reading I get This
The Setting line is [����sr��java.util.ArrayListx����a���I��sizexp������w������t��]
The Setting line is [����sr��java.util.ArrayListx����a���I��sizexp������w������t��, test#test.comt��passwordt�� itdguccgjx]
and I need like this
test#test.com
password
itdguccgjx
What is wrong?
Sorry for my bad English.
Hi
I will like this.
Textbox1
Textbox2
Textbox3
.......
If I will get value of arraylist.get(1).tostring I get Textbox2
I have a text file is conten.txt which has
101,1,123
102,1,234
I am using Android to update that text file. With a input as "102", I want to update second line with information is "2,234". So it will be
102,2,234
Finally, the content in text file will be
101,1,123
102,2,234
Is it possible to do it in Android? This is my current work. However, tt only writes a new line in the file
String whole_content="102,2,234";
File file = new File(getApplicationContext().getFilesDir(), "conten.txt");
String filepath = Environment.getExternalStorageDirectory().getPath();
FileOutputStream outputStream;
try {
outputStream = openFileOutput("conten.txt", Context.MODE_PRIVATE);
outputStream.write(whole_content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Yes it's possible! Simply, you could create a string of total file content and replace all the occurrence in the string and write that string to that file again.
File log= new File("yourFile");
String search = "102"; //Like you said
try{
FileReader fr = new FileReader(log);
String s;
String totalStr = "";
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
if(s.contain(search)) {
s = search + "," + "yourReplaceString"; //You can extract it from your input
}
totolStr += s;
}
FileWriter fw = new FileWriter(log);
fw.write(totalStr);
fw.close();
}
}catch(Exception e){
e.printStackTrace();
}
I have three strings which write in to list.txt file with this code
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ;
FileOutputStream fop = null;
File file = null;
try {
file =new File(filename);
fop=new FileOutputStream(file,true);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
filecontent=filecontent+ System.getProperty ("line.separator");
// get the content in bytes
byte[] contentInBytes = filecontent.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (IOException e) {
e.printStackTrace();
}
The file output detail is
abc.mp3
cde.mp3
edf.mp3
Now, I want to read the detail in list.txt. I used below code but the output only has
cde.mp3
edf.mp3
What is happen with my code? I don't know why data abc.mp3 disappear.
ArrayList<String> data;
try {
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ;
BufferedReader in = new BufferedReader(new FileReader(filename));
String audio_name;
audio_name = in.readLine();
data = new ArrayList<String>();
while ((audio_name = in.readLine()) != null) {
data.add(audio_name);
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
for (int i=0;i<data.size();i++)
{
Log.d("D",String.valueOf(data.get(i)));
}
The first instance of audio_name = in.readLine() would read the first line abc.mp3 but the input is not used. Thus first line read by your while loop and stored in data would be cde.mp3. You should remove the first instance of audio_name = in.readLine().
audio_name = in.readLine();
data = new ArrayList<String>();
You read your first line into your audio_name variable, but you never add it to the list, so that's why it's "missing".
Hi i have a string that contains html and css that i want to load into a WebView as a file. so i want to create a Directory on the internal storage i don't really want to store it on an SDCard as the file i'm saving contains important information. I then want to create a mFile.html not that directory. And the final step is then return the file to load into a WebView. Does anyone know how to do this?
heres what i have tried so far
public static void writeFileToDirectory(Context activityContext, String writableString,String folderName, String fileName){
File myDir = activityContext.getFilesDir();
try {
File secondFile = new File(myDir + "/" + folderName + "/", fileName);
if (secondFile.getParentFile().mkdirs()) {
secondFile.createNewFile();
FileOutputStream fos = new FileOutputStream(secondFile);
fos.write(writableString.getBytes());
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File secondInputFile = new File(myDir + "/html/", fileName);
InputStream secondInputStream = new BufferedInputStream(new FileInputStream(secondInputFile));
BufferedReader r = new BufferedReader(new InputStreamReader(secondInputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
secondInputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
try this
File myDir = activityContext.getFilesDir();
try {
File secondFile = new File(myDir + "/" + folderName);
if(!secondFile.exists())
{
secondFile.mkdir();
}
FileOutputStream fos = new FileOutputStream(secondFile.getAbsolutePath()+"/"+fileaName);
fos.write(writableString.getBytes());
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
What's wrong with the code? I added the permission already. Logcat isn't printing the message it's supposed to show.
I'm guessing I have to use a filestream?
public class Run {
int abc = 2;
int[] myIntArray = {1,2,3};
String texts = "abcabac";
//Person p = new Person();
Paragraph p = new Paragraph(abc, texts, myIntArray);
Serializer serializer = new Persister();
File file = new File("paragraphs.xml");
private final static String TAG = Run.class.getCanonicalName();
String a = "writeing something nothing";
// Now write the level out to a file
Serializer serial = new Persister();
//File sdDir = Environment.getExternalStorageDirectory(); should use this??
//File sdcardFile = new File("/sdcard/paragraphs.xml");
File sdcardFile = new File(Environment.getExternalStorageDirectory().getPath());
{
try {
serial.write(p, 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());
}
I have samsung galaxy s3 with android 4.1.2. My internal phone memory is named sdcard0 and my external card extSdCard.
Environment.getExternalStorageDirectory()
So the above returns the path of sdcard0 which is internal phone memory
In such cases to get the actual path you can use the below
String externalpath = new String();
String internalpath = new String();
public void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.contains("secure")) continue;
if (line.contains("asec")) continue;
if (line.contains("fat")) {//external card
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
externalpath = externalpath.concat("*" + columns[1] + "\n");
}
}
else if (line.contains("fuse")) {//internal storage
String columns[] = line.split(" ");
if (columns != null && columns.length > 1) {
internalpath = internalpath.concat(columns[1] + "\n");
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Path of sd card external............"+externalpath);
System.out.println("Path of internal memory............"+internalpath);
}
Once you get the path you can use the below.
Try the below
String filename = "filename.xml";
File file = new File(Environment.getExternalStorageDirectory(), filename);
//Instead of Environment.getExternalStorageDirectory() you can use internalpath or externalpath from the above code.
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
//to get sdcard path
String sdcardpath = Environment.getExternalStorageDirectory().getPath();
//to write a file in sd card
File file = new File("/sdcard/FileName.txt");
if (!file.exists()) {
file.mkdirs();
}
Permission to add in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
you have to do
filename is test.xml,text.jpg or test.txt
File sdcardFile = new File(Environment.getExternalStorageDirectory()+"/"+filename);
cehck this link.
for more detail about External Storage