I am trying to create a logfile of RSSI values and RSSI values once a filter has been applied. I do not want to use the android logfile. I want to use a text file that I can export to excel. This is the code that I have written. I am new to android, but have some java experience.
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.d("MainActivity", "MEDIA_MOUNTED is true");
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS);
File file = new File(path, "RSSI.txt");
try {
pw = new PrintWriter(new FileWriter(file), true);
pw.print(beacon.getRssi());
pw.print(kalman.kalman(rssis));
pw.println();
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
you can try creating a new file if it doesn't exist
if(!file.exists())
{
file.createNewFile()
// you can start writing to file from here.
}
make sure to add permission to read and write from the external storage in the manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
I would like to delete an internal file at runtime. When I download from an external server, the old version of the file (with the same name) is replaced, however I am unable to read it. I think that I need to delete the previous file before downloading the new version. Here is an example of what I have tried so far:
try {
FileOutputStream fos = getApplicationContext().openFileOutput("mytext.txt", Context.MODE_PRIVATE);
fos.write(getStringFromFile(pictosFile.getAbsolutePath()).getBytes());
Log.e("mytextfile",""+getStringFromFile(pictosFile.getAbsolutePath()));
progressDialog.cancel();
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
This allows me to save the file into internal memory, but I am unsure about how to delete the previous file before writing the new version.
If you need to ensure that the file is overwritten, i.e. delete an old copy before saving a new version, you can use the exists() method for a file object. Here is an example showing how to delete an old version of an image file before writing a new file with the same name in a nested directory:
// Here TARGET_BASE_PATH is the path to the base folder
// where the file is to be stored
// 1 - Check that the file exists and delete if it does
File myDir = new File(TARGET_BASE_PATH);
// Create the nested directory structure if it does not exist (first write)
if(!myDir.exists())
myDir.mkdirs();
String fname = "my_new_image.jpg";
File file = new File(myDir,fname);
// Delete the previous versions of the file if it exists
if(file.exists())
file.delete();
String filename = file.toString();
BufferedOutputStream bos = null;
// 2 - Write the new version of the file to the same location
try{
bos = new BufferedOutputStream(new FileOutputStream(filename));
Bitmap bmp = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buf);
bmp.compress(Bitmap.CompressFormat.PNG,90,bos);
bmp.recycle();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
finally{
try{
if(bos != null)
bos.close();
}
catch(IOException e){
e.printStackTrace();
}
}
You must also ensure that you have read / write access to memory, make sure that you ask the user for these permissions at run time and have the following in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I am trying to append text into a file stored in emulated/0/.. folder (external storage without SD Card)
FileOutputStream fileOutputStream = new FileOutputStream(capturesFile, true);
OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
String data = "my data";
writer.append(data);
writer.close();
fileOutputStream.flush();
fileOutputStream.close();
This code is not working, I really do not understand why. Is the emulated location is a problem (stupid question but at this point...) I already tried many ways without any positive solution.
Is someone have an idea about this issue.
Use this code
try {
FileWriter fw = new FileWriter("path/of/file",true);
fw.write("myData");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
First make sure you've given the required permission to write a file and that would be -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in Manifest file and
if (ContextCompat.checkSelfPermission(context,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_EXT_STORAGE);
}
in your activity.
Second please check your directory path. There might be some chances that you are using a wrong path. Easiest way to get a direct path for the Internal Storage is -
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data" + getApplicationContext().getPackageName();
File file = new File(path + "/File.txt");
You can use this method as per your requirement to write a file -
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.append("My Data");
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
I want to write a file to external storage in android but get the FileNotFoundException. I have put the permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
in my manifest and if I do a check like
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
it returns true. I have tried different solutions from questions from SO (Android saving file to external storage; Write a file in external storage in Android; Writing to external storage filenotfoundexception) but none seemed to work for me. Sorry for posting a duplicate question but Ive been searching for days and couldnt find an answer.
My Code is the following:
private void Writing(String erg) {
TextView one = (TextView) findViewById(R.id.e1);
File root = android.os.Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File dir = new File (root.getAbsolutePath());
dir.mkdirs();
File file = new File(dir, "Test.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(erg);
pw.flush();
pw.close();
f.close();
one.setText("File created");
} catch (FileNotFoundException e) {
e.printStackTrace();
one.setText("Error1");
} catch (IOException e) {
e.printStackTrace();
one.setText("Error2");
}
}
The Textview one ends up with printing Error1.
I'll appreciate any help.
I am writing an android application. In the MainActivity.java, I created a method to write and then read contents from a file. These code runs successfully I and can store the data in a file named abc.txt, but I cannot find the written file in ES File Explorer.
public void writeInIt(View view) {
try {
String Message = editText.getText().toString();
final File myFile = new File("abc.txt");
if (!myFile.exists()) {myFile.createNewFile(); }
FileOutputStream outputStream = new FileOutputStream(myFile);
outputStream.write(Message.getBytes());
outputStream.close();
editText.setText("");
Toast.makeText(getApplicationContext(), "Message Saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Where does it save the file? Why I can't I search it through the File Explorer?
Ref to "http://developer.android.com/reference/java/io/File.html", if i include path, it will definitely store in that path location. However, if I not locate the dir, it can still store in device, but where does the file actually save???
"File file = new file(filename)"
this code does not save anything, it only cretes a class wrapper for file or director path. The closest method to actually create file would be to use file.createNewFile method.
There is guide for writing files from google: Saving Files
[edit]
following code generates exception "open failed: EROFS (Read-only file system)":
File fl = new File("test12.txt");
try {
fl.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
In Android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this is the code :
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
You can find this file in device manager.
Click your device (file symbol)
/data/user/0/com.example.myapplication/files and than follow this path
I am trying to write files in the external SD card folder. Even after having set the required permission in the manifest file, I am unable to write on the external SD card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Code:
String path = "/mnt/extsd/nit.txt";
File myFile = new File(path);
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
}
try {
FileOutputStream fostream = new FileOutputStream(myFile);
OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);
bwriter.write("Hi welcome ");
bwriter.newLine();
bwriter.close();
oswriter.close();
fostream.close();
txtText.setText("success");
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
On the other hand when I use ES File Explorer and try to create a file, it creates it without any issues.
Don't use the absolute path String path = "/mnt/extsd/nit.txt"; because you never know about android device being used by users. Rather you can get the external storage directory path by using Environment.getExternalStorageDirectory().toString().
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.
File log = new File(Environment.getExternalStorageDirectory(), "your_file_name.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write("any data");
} catch (Exception e) {
}
And don't forget to close the streams.
First check sd-card is available or not.
String state = Environment.getExternalStorageState();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File folder = folder = new File(extStorageDirectory, "FolderName");
if(!folder.exists())
{
folder.mkdir();//making folder
}
File file = new File(folder,"Filename");//making file
}
Please try this code, it work in my application.