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
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 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.
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".
i wanted to show only .xml files to user which is currently present in the sd card.i try the following but it shows all files in my sdcard including directories
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/xml");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select XML File"), SelectXMLFILE);
Use the following code and manipulate it according to your needs
File sdcardPath = new File(Environment.getExternalStorageDirectory().getPath() +"/SomeFolder");
List<String> list;
list = new ArrayList<String>();
list=sdcardPath.listFiles();
Now loop through the list and check each file name and apply endWith("xml"); function on the items to get all xml files. Hope it works.
Loop in it like that
List<String> XMLFiles= new ArrayList<String>();
for(int i=0; i<=list.size(); i++)
{
XMLFiles.add(list.get(i).endsWith("xml"));
}
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.
File dir= new File(android.os.Environment.getExternalStorageDirectory());
//Instead of android.os.Environment.getExternalStorageDirectory() you can use internalpath or externalpath
Then call
walkdir(dir);
ArrayList<String> filepath= new ArrayList<String>();//contains list of all files ending with .xml
public void walkdir(File dir) {
String xmlPattern = ".xml";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(xmlPattern)){
//Do what ever u want
filepath.add( listFile[i].getAbsolutePath());
}
}
}
}
}
I want to create a directory on "/mnt/extsd/MyFolder" this path. while calling mkdir() it returns false.I inserted the sdcard on my tablet, got the external path as "/mnt/extsd" and trying to create a folder on this path. Below is my code,
File lSDCardDirFile = new File("/mnt/extsd/MyFolder");
if (!lSDCardDirFile.exists()) {
System.out.println("Is folder created --- " + lSDCardDirFile.mkdirs());
}
I gave the permissions, .
I want to create the folder in External sd card which is removable sd card.
I am using android 4.0 ICS version device.
I created a different method for getting paths fom external SD card,
public static String[] getStorageDirectories()
{
String[] lDirs = null;
BufferedReader lBufferReader = null;
try {
lBufferReader = new BufferedReader(new FileReader("/proc/mounts"));
ArrayList list = new ArrayList();
String lStrline;
while ((lStrline = lBufferReader.readLine()) != null) {
if (lStrline.contains("vfat") || lStrline.contains("/mnt")) {
StringTokenizer lTokenizer = new StringTokenizer(lStrline, " ");
String lStrPath = lTokenizer.nextToken();
lStrPath = lTokenizer.nextToken(); // Take the second token, i.e. mount point
if (lStrPath.equals(Environment.getExternalStorageDirectory().getPath())) {
list.add(lStrPath);
}
else if (lStrline.contains("/dev/block/vold")) {
if (!lStrline.contains("/mnt/secure") && !lStrline.contains("/mnt/asec") && !lStrline.contains("/mnt/obb") && !lStrline.contains("/dev/mapper") && !lStrline.contains("tmpfs")) {
list.add(lStrPath);
}
}
}
}
lDirs = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
lDirs[i] = (String) list.get(i);
}
}
catch (FileNotFoundException e) {}
catch (IOException e) {}
finally {
if (lBufferReader != null) {
try {
lBufferReader.close();
} catch (IOException e) {
}
}
}
return lDirs;
}`
From this method I got the path, but while trying to create a directory, the mkdir() returns false.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I have two folders like extSdCard and sdcard in my samsung galaxy s3.
Use the below code to choose.
private String[] mFilePaths;
File storageDir = new File("/mnt/");
if(storageDir.isDirectory()){
File[] dirList = storageDir.listFiles();
for (int i = 0; i < dirList.length; i++)
{
mFilePaths[i] = dirList[i].getAbsolutePath();
System.out.println("...................................."+mFilePaths[i]);
}
}
File Dir;
if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))//check if sd card is mounted
{
Dir=new File(android.os.Environment.getExternalStorageDirectory(),"your folder name");
if(!Dir.exists())// if directory is not here
Dir.mkdirs() // make directory
}
Edit
To get the paths of internal and external storage. below code works on samsung galaxy s3.
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);
}
Now you can use the path os external storage to create a folder.
if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))//check if sd card is mounted
{
Dir=new File(externalpath,"your folder name");
if(!Dir.exists())// if directory is not here
Dir.mkdirs() // make directory
}
Do you have declared permission in Manifest.xml file?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also I suggest you to not going for HardCoded path of /mnt/extsd/ Instead of it just use Environment.getExternalStorageDirectory().getPath().
final String PATH = Environment.getExternalStorageDirectory() + "/myfolder/";
if(!(new File(PATH)).exists())
new File(PATH).mkdirs();
include permission in manifest::
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Add permission in Manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
File sdDir = Environment.getExternalStorageDirectory();