I want to write or place my file in Android Internal storage and I am doing this -
try {
File file = new File("/data/local/measurement.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content.toString());
bw.close();
Log.d("hi", "WRITTEN");
} catch (IOException e) {
e.printStackTrace();
}
I already have measurement.txt in /data/local path but nothing is being written to it. I am using emulator and I have also given permissions like
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(context.openFileOutput("myfile", MODE_PRIVATE)));
out.write(string);
out.close();
This will put the file in /data/data/<pkg>/files, private to your app, where it belongs. You don't need any permissions for this.
Related
Can't write my string to file on external storage. I have write and read external storage permissions in Manifest. Also added this one
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
from previous similar questions. But nothing seems to work. Thanks in advance
if (isSDCARDAvailable()) {
writeToFile(resultJson.toString());
}else {
Log.d(TAG, "false");
}
private void writeToFile(String string){
String filename = "routes.txt";
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard.getPath(), filename);
try {
FileWriter writer = new FileWriter(file);
writer.write(string);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean isSDCARDAvailable(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
Please use this permission instead of mount and unmount, it will work. If it does not, please paste the error you are getting.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If every lane is executed, Log the string to see if it's empty ?
I am trying use Android Studio emulation to produce a json in my apps. Is there a way to locate the directory and set it as path and implement it in the following?
......
DIRECTORY directory = createDummySchool();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(filepath? + "sample.json"), directory);
}catch (IOException e) {
e.printStackTrace();}
.....
well it depends where you want to write your file in, Internal or external memory.
you can always write information in internal memory which can be accessible by your app but to write on external memory you will require permission like
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
To save file internally you can use this
getFilesDir();
String filename = "myfile";
File file = new File(context.getFilesDir(), filename);
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
refer this for more information, this is the best way and should be the first place where you should be looking, :)
I have been working on this for a few weeks now a little bit at a time. This is an android app i am developing for multiple versions of Samsung tablets. I need to create a file and add text to it. I cannot do either. I have 2 different methods to add text using different text writers to add text to a file. Here is my code:
public void addTextToFile(String text) {
File logFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS), "MyFile.csv");
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(String data){
OutputStream os;
OutputStreamWriter osw;
data += "\n";
try {
os = new FileOutputStream(file, true);
osw = new OutputStreamWriter(os);
osw.write(data);
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Found my error, I did research at the beginning and thought i did not need permission to create a publicly view-able file, I gave myself permission in the android manifest like so:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I want to create a .txt file and store it on the external storage of the Android phone. I added the permission to my Android Manifest. When I run the code it doesn't give me any error but the file is never created. Not sure what I am doing wrong.
public void createExternalStoragePrivateFile(String data) {
// Create a path where we will place our private file on external
// storage.
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = null;
OutputStreamWriter out = null;
os = myContext.openFileOutput(data, Context.MODE_PRIVATE);
out = new OutputStreamWriter(os);
out.write(data);
os.close();
if(hasExternalStoragePrivateFile()) {
Log.w("ExternalStorageFileCreation", "File Created");
} else {
Log.w("ExternalStorageFileCreation", "File Not Created");
}
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
you need an appropriate permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file, true);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(data);
out.close();
}
I was able to create the file on the external storage by using the code below:
public void createExternalStoragePrivateFile(String data) {
// Create a path where we will place our private file on external
// storage.
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(data);
out.close();
if(hasExternalStoragePrivateFile()) {
Log.w("ExternalStorageFileCreation", "File Created");
} else {
Log.w("ExternalStorageFileCreation", "File Not Created");
}
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
I'm trying to write a file from an Http post reply to a file on the sdcard. Everything works fine until the byte array of data is retrieved.
I've tried setting WRITE_EXTERNAL_STORAGE permission in the manifest
and tried many different combinations of tutorials I found on the net.
All I could find was using the openFileOutput("",MODE_WORLD_READABLE) method, of the activity but how my app writes file is by using a thread. Specifically, a thread is invoked from another thread when a file has to be written,
so giving an activity object didn't work even though I tried it.
The app has come a long way and I cannot change how the app is currently written.
Please, someone help me?
CODE:
File file = new File(bgdmanip.savLocation);
FileOutputStream filecon = null;
filecon = new FileOutputStream(file);
byte[] myByte;
myByte = Base64Coder.decode(seReply);
bos.write(myByte);
filecon.write(myByte);
myvals = x * 11024;
bgdmanip.savLocation holds the whole files path. seReply is a string reply from HttpPost response. The second set of code is looped with reference to x. The file is created but remains 0 bytes.
//------------------------------WRITING DATA TO THE FILE ---------------------------------
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(v.getContext(),"Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
}
catch (Exception e)
{
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
//---------------------------READING DATA FROM THE FILE PLACED IN SDCARD-------------------//
btnReadSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null)
{
aBuffer += aDataRow ;
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(v.getContext(),"Done reading SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
ALONG WITH THIS ALSO WRITE THIS PERMISSION IN Android.Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The openFileOutput() method writes data to your application's private data area (not the SD card), so that's probably not what you want. You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
Here is a sample:
// Log used as debug
File log = new File(Environment.getExternalStorageDirectory(), "Log.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write(new Date().toString());
out.write(" : \n");
} catch (Exception e) {
Log.e(TAG, "Error opening Log.", e);
}