I have this code for write and read to file ZIZI.txt:
//=============== Write To File ZIZI.txt ===============================================
private void writeFileToInternalStorage() {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput(
"ZIZI.txt", MODE_WORLD_WRITEABLE)));
writer.write("This is a test1." + eol);
writer.write("This is a test2." + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getBaseContext(),"OK Save", Toast.LENGTH_SHORT).show();
}
//================ Read From File ZIZI.txt ===========================================
private void readFileFromInternalStorage() {
String FF="";
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(openFileInput("ZIZI.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
FF+=line+eol;
buffer.append(line + eol);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getBaseContext(),FF, Toast.LENGTH_SHORT).show();
}
I see with DDMS that the File is in: \data\data\setup.myProject\files\ZIZI.txt
But I can't see this file in my phone (because I don't have root permissions)
I want to write and read from my SD card or from any folder that I can see in my
phone. How to change the code for this?
Have you never used the Android Developers website?
Try Dev Guide -> Data Storage -> Using the External Storage
You need to specify the entire path to your file, using either getFilesDir for internal storage or getExternalFilesDir() for external storage. For example:
openFileInput(getExternalFilesDir(null) + "/" + "ZIZI.txt");
Related
My minSdkVersion is 16, I hope to get all storage (include internal and external) and absolute path.
The absolute path maybe like /storage/sdcard0/, how can I do? Thanks!
You can read the kernel exported file /proc/mounts to get the entire list of mounted file system on your device. The seconds column from /proc/mounts is the mounted point.
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/mounts")));
List<String> mountPoints = new ArrayList<>();
String l;
while ((l = reader.readLine()) != null) {
String p = l.split("\\s+")[1];
if (p != null && p.startsWith(File.separator)) {
mountPoints.add(p);
}
}
Log.d(TAG, "all mount absolute points " + Arrays.toString(mountPoints.toArray()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
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;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.
I am trying firstly to download the file and its content from Dropbox in Android app using Dropbox Core API but when i execute the following code the app crushes.
EDIT: I have used two functions downloadDropboxFile and copy functions. The problem is that i am getting blank data when i read the local file which is supposed to contain the dropbox file data.
Here is the code where i call the function
downloadDropboxFile("/userandpass.txt");
if (mDBApi.getSession().isLinked())
{
InputStream instream = new FileInputStream(String.valueOf(getExternalCacheDir()) + "/userandpass.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
mTestOutput.setText(buffreader.readLine());
}
Here is the functions
private boolean downloadDropboxFile(String fileSelected) {
File dir = new File(String.valueOf(getExternalCacheDir()));
if (!dir.exists())
dir.mkdirs();
try {
File localFile = new File(dir + fileSelected);
if (!localFile.exists()) {
localFile.createNewFile();
copy(fileSelected, localFile);
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
private void copy(final String dbPath, final File localFile) {
new Thread(new Runnable() {
#Override
public void run() {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
DropboxAPI.DropboxInputStream fd = mDBApi.getFileStream(dbPath,null);
br = new BufferedInputStream(fd);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}). start();
}
Dropbox Core API Implementation on Android Studio:
On app/libs i have the:
dropbox-android-sdk-1.6.3.jar
httpmime--4.0.3.jar
json_simple-1.1.jar
Your issue is here :
if (!localFile.exists()) {
localFile.createNewFile(); //otherwise dropbox client will fail silently
}
The exception is :
java.io.IOException: open failed: EROFS (Read-only file system)
This means you're trying to create a File on a location that is read only in the phone's memory, I'm guessing the internal storage. Have a look at this excellent answer by Mark Murphy on creating a File based on locations that can be written to.
Hoping this has been of some help, happy coding ;-)
I have a txt file in the root folder of my Android project called KARIN.txt. I am trying to reach it by FileReader but I am having the following error:
java.io.FileNotFoundException: /KARIN.txt: open failed: ENOENT (No such file or directory)
How I am trying to reach that file is as following:
BufferedReader br = new BufferedReader(new FileReader("KARIN.txt"));
I am confused that why it is not allowing me to read the file.
If KARIN.txt is built into your project you should put it in the assets folder and access it via the AssetManager.
public String loadFile(String file){
AssetManager am = getActivity().getAssets();
InputStreamReader ims = null;
BufferedReader reader = null;
String data = "File not available!";
try {
ims = new InputStreamReader(am.open(file), "UTF-8");
reader = new BufferedReader(ims);
} catch (IOException e) {
e.printStackTrace();
}
if(ims != null){
try {
String mLine = reader.readLine();
data = "";
while(mLine != null){
data+= mLine;
mLine = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return data;
}
private void readFileFromSDCard() {
File directory = Environment.getExternalStorageDirectory();
File file = new File(directory+"/HomeActivityLogs");
//file.getParentFile().mkdirs();
if (!file.exists()) {
FileWriter gpxwriter;
try {
System.out.println(" IN TRY Error");
file.createNewFile();
gpxwriter = new FileWriter(file);
System.out.println(" file writer Error");
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("http://192.168.1.126/msfaws2_4/Service.asmx");
System.out.println(" in url Error");
/// out.write("http://192.168.1.250/msfaws2_4/Service.asmx");
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
loginLog.appendLog("Exception in readFileFromSDCard() " + e.getMessage(),"MainActivity");
}
}
BufferedReader reader = null;
try {
System.out.println("Error");
reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Constant.URL = builder.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
loginLog.appendLog("Exception in readFileFromSDCard() " + e.getMessage(),"MainActivity");
}
}
}
}
Please help me to solve this. It gives an error filenotfound with the filename
it creates dynamically from the web services, when the data was stored temporary and then retrieved from the activity.
Try this, Add this permission in you manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />