I'm writing a android app that writes the accelerometer values to a file, I'm getting the values to show up on the screen but I don't know if it is writing them to a file, and if it is I can't find the file.
I have this method, but I'm not sure if it is doing it right;
public void WriteToFile()
{
try
{
final String accelValue = new String(accelXValue + "," + accelYValue + "," + accelZValue);
FileOutputStream fOut = openFileOutput("accelValue.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(accelValue);
osw.flush();
osw.close();
}
finally
{
return;
}
}
Where would this store the file on a phone?
Should I call this somewhere in my code or is it OK that it follows the accelerometer methods?
Thanks.
Also, the app needs to create the file its writing to.
https://stackoverflow.com/a/8738467/1383281
Would this answer help?
Here's the new code but it still doesn't seem to do anything.
public void WriteToFile()
{
File AccelData = new File(Environment.getExternalStorageDirectory() + File.separator + "AccelData.txt");
try
{
if (!(AccelData.exists()))
{
AccelData.createNewFile();
}
final String accelValue = new String(accelXValue + "," + accelYValue + "," + accelZValue);
FileOutputStream ADOut = openFileOutput("accelValue.txt", MODE_WORLD_READABLE);
OutputStreamWriter AD = new OutputStreamWriter(ADOut);
AD.write(accelValue);
}
finally
{
return;
}
}
public void WriteToFile()
{
FileOutputStream fOut = openFileOutput("accelValue.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try
{
final String accelValue = new String(accelXValue + "," + accelYValue + "," + accelZValue);
// Write the string to the file
osw.write(accelValue);
}
finally
{
osw.flush();
osw.close();
return;
}
}
Check
http://developer.android.com/guide/topics/data/data-storage.html
for different options to write to a file. You basically can write to
Internal Storage - Store private data on the device memory.
External Storage - Store public data on the shared external storage.
and must take care of permission etc.
Related
I am a beginner when it comes to Android. I encountered a problem, regarding writing to a file. I want to save to a file the input I get in a form. However, the piece of code that I wrote is not writing in my file. Could anyone please help me?
The code looks like that:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder s = new StringBuilder();
s.append("Event name: " + editText1.getText() + "|");
s.append("Date: " + editText2.getText() + "|");
s.append("Details: " + editText3.getText() + "|");
File file = new File("D:\\config.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024);
out.write(s.toString());
out.newLine();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
So, I have a form containing 3 fields: the name of an event, the date and the description. These I want to save to my file. I should mention that I use an emulator for testing.
Use following path for file. It will write file to your root folder of storage.
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file= new File(extStorageDirectory, "config.txt");
writeToFile("File content".getBytes(), file);
writeToFile
public static void writeToFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
Don't forget to add following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
https://github.com/rznazn/GPS-Data-Logger/blob/master/app/src/main/java/com/example/android/gpsdatalogger/StorageManager.java
Here is a... nearly complete class for writing to the documents folder on the emulated external storage of the device.
Don't forget to add the write permissions to manifest.
I have created a simple application to take some user data and write it to a text file which gets saved on the external storage of my device. However, I am unable to access those files using my computer until after I have rebooted my device. Can anyone tell me why this is and if there is something I can do to fix it?
Here is the code I use to write data.
private void commitToFile(String worldOrApp, String xPos, String yPos, String orient) {
Intent intent = getIntent();
String filename = intent.getStringExtra(MainActivity.FILENAME) + ".txt";
final String position = worldOrApp + " - x: " + xPos + "; y: " + yPos + "; alpha: " + orient + "\r\n";
File myPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFolder = new File(myPath.getAbsolutePath()+"/test_folder");
if (!myFolder.exists()) {
myFolder.mkdirs();
}
File myFile = new File(myFolder, filename);
try {
FileOutputStream fileOutputStream = new FileOutputStream(myFile, true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
outputStreamWriter.write(position);
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks to #CommonsWare for the direction. I found the following code at Android saving file to external storage
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
which I placed directly underneath the exception catch in my code, and updated file to myFile, which is the relevant File for my commitToFile method.
I'm creating some text files and save them with a timestamp in the method below:
private void writeToFile(String data) {
try {
Long tsLong = System.currentTimeMillis() / 1000;
String fileName = tsLong.toString() + "ds.txt";
Log.i("FILENAME", fileName);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(fileName, Context.MODE_PRIVATE));
outputStreamWriter.write(data + "\r\n");
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("FAILED", "File write failed: " + e.toString());
}
}
Now in order to read from the files, I need the filenames. Is there any way to generate a list of all the files in that repository?
As njzk2 mentioned you can get the dir where the files are saved via the getFilesDir() method.
Example code:
for(File file : getFilesDir().listFiles()){
// Open file and read the content
}
If you mean with repository a folder on Android device then you need this snippet of code
File path = new File(mCurrentPath);
File[] dirs = path.listFiles();
List<String> files = new ArrayList<String>();
if (dirs != null) {
Arrays.sort(dirs);
for (File fentry : dirs) {
if (!fentry.isDirectory()) {
files.add(fentry.getName());
}
}
}
I'm developing an app in which I'm sending a .txt file from one end by attaching it with gmail. Everytime this file is sent, its name is data.txt. When this file is downloaded at the other end, on the first download its name is the same, i.e. data.txt. However, when another file is sent with the same name, the name of the file at the receiveing end becomes data-1.txt, data-2.txt etc. And because of this, I'm not able to read the proper file. Please could someone give me some suggestions to solve this problem? The sending and receiving code is given below: SEND
bSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
String toWrite = enterText.getText().toString();
FileOutputStream fos;
try {
String path = Environment.getExternalStorageDirectory().toString();
Log.v("path", path);
File myFile = new File("" + path + "/" + fileName + ".txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(toWrite);
Log.v("file written", toWrite);
myOutWriter.close();
fOut.close();
Uri u1 = null;
u1 = Uri.fromFile(myFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "MPPT Configuration Data");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
READ:
bRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/storage/sdcard0/download/" + fileName + ".txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
Log.v("read data", "" + aBuffer);
tvData.setText(aBuffer);
}catch (IOException e2) {
e2.printStackTrace();
}
}
});
I found a possible solution. I can link the file manager (external app) from where the user can pick out whichever file he wants to be read.
Thanks #greenapps fir the idea of displaying a list of files.
You can get all the file by using regex ,then process the file by following way:
1.if only one file found,read it;
2.if more than one file found, compare and read the file which last number is biggest
but this solution still has one problem,if has file data.txt and data-3.txt ,the file we want to read may become data-2.txt,but what we really read is data-3.txt.
Or,maybe you can get the file you want by judging file established time.
I am using this code as a part to write data to a text file, but I am not sure how I can append the data to the new line. "\n" does not seem to be working. Here, variable "data" has this format:
t=1, x=-3.1, y=19.0, z=-8.6
this part of the code iterates and the variable "data" is written each time; the current result is something like:
t=1, x=-6.9, y=-9.6, z=-6.9t=2, x=-1.4, y=6.2, z=7.0t=3, x=-1.4, y=6.1, z=6.9t=4, and so on, but what I would like is:
t=1, x=-6.9, y=-9.6, z=-6.9
t=2, x=-1.4, y=6.2, z=7.0
t=3, x=-1.4, y=6.1, z=6.9
Thanks in advance for your help.
String datatest = data.toString();
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/test");
directory.mkdirs();
String filename = "test.txt";
File file = new File(directory, filename);
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(datatest + "\n");
osw.flush();
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
try "\r\n"
and to make this answer longer :)