How can I write data to text file inside an Android device?
As of now I am sending that data to server which writes it in json format. However, I want my program to write my data inside Android directly.
I want to record sensor values every time when sensors change their values. I have the following code:
What should I put instead of comment?
public void onSensorChanged(SensorEvent event)
{
switch(event.sensor.getType())
{
case Sensor.TYPE_LINEAR_ACCELERATION:
//writing event.values[0], event.values[1] and event.values[2] to result.txt
break;
..........
}
}
String strContent = "Write File using Java FileOutputStream example !";
FileOutputStream fileOut = openFileOutput(outputFile, MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fileOut);
osw.writeBytes(strContent.getBytes());
osw.flush();
Other code:
File logFile = new File("sdcard/log.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
I would not write the file everytime sensot is changed, but rather would build a String with only relevant data and write it to the file at the end of the process.
Related
The app is to write some data every second on file. This is working in other tabs & phones but in "Lenovo IdeaTab" (4.1) is able to create directory but not able to create file to write in it.
Below is the code, I am using to write in file:
public void writeDataInFile(String dataString)
{ File logFile = null;
try {
File folder = new File(Environment.getExternalStorageDirectory() + "/file_name_xyz");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
String file_path = folder+"/"+currentFileName+".txt";
logFile = new File(file_path);
if (!logFile.exists())
{
try
{
logFile.createNewFile();
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append("\nxyz: \n");
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
// Do something else on failure
Toast.makeText(getApplicationContext(), "Failed to write", Toast.LENGTH_SHORT).show();
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(dataString);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
//Write internal storage -- data/data/xyzzz
try {
FileOutputStream fos = openFileOutput(currentFileName, Context.MODE_APPEND);
fos.write(dataString.getBytes());
fos.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
Verify which version of Android is installed on the Tablet and then lookup file IO API in the Android Docs for that version of Android. I'm pretty sure they changed some things when it comes to accessing files in some of the later versions of the API.
Honestly, I've searched a lot do this task so I ended up trying various methods but nothing worked until I ended up on this code. It works for me perfectly like it should, so I do not want to change my code.
The help I need is to put this code in a such a way that it begins to read a file, but if it the file doesn't exist then it will create a new file.
Code for saving data:
String data = sharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Code for loading data:
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte [fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So If I add the saving data code in to the "FileNotFoundException" catch of the loading data part then could I achieve what I want?
Add
File file = new File(FILENAME);
if(!file.exists())
{
file.createNewFile()
// write code for saving data to the file
}
above
fis = openFileInput(FILENAME);
This will check if there exists a File for the given FILENAME and if it doesn't it will create a new one.
If you're working on Android, why don't you use the API's solution for saving files?
Quoting:
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
You should really read the whole document, they explain pretty well the basic ways of creating or accessing files, you can also check the different ways of storing data.
But regarding your original question:
So If I add the saving data code in to the "FileNotFoundException"
catch of the loading data part then could I achieve what I want?
Yes, you could achieve it.
Try this one:
public static void readData() throws IOException
{
File file = new File(path, filename);
if (!file.isFile() && !file.createNewFile()){
throw new IOException("Error creating new file: " + file.getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try {
// ...
// read data
// ...
}finally{
r.close();
}
}
Ref: Java read a file, if it doesn't exist create it
I want to write some information about users to reuse them but I cannot create a text file so I cannot read it, too. Before starting to read, I want to accomplish writing to text file.
I wrote the user permission into manifest file.
Also, my code for writing into text file as in below:
public static void writeFile(String item, String fileName) throws IOException {
BufferedWriter out;
try {
FileWriter fileWriter= new FileWriter(Environment.getExternalStorageDirectory().getPath()+"/"+fileName);
out = new BufferedWriter(fileWriter);
out.write(item);
out.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
So can anyone say the problem? Thank you.
As far I understood, you may want to use sharedpreferences, take a look: Simple Example Sharedpreferences
You can store and retrieve data easily...
Anyway...
Make sure your manifest contains:
1. android:name="android.permission.READ_EXTERNAL_STORAGE
2. android:name="android.permission.WRITE_EXTERNAL_STORAGE
String string1 = "Hey you";
FileOutputStream fos ;
try {
fos = new FileOutputStream("/sdcard/filename.txt", true);
FileWriter fWriter;
try {
fWriter = new FileWriter(fos.getFD());
fWriter.write("hi");
fWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.getFD().sync();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
i have problem with file writing. I want to create OnClick method of button that add line to file on sdcard but instead it delete previous line and put all content in place of current one. In result i got only the Text i put at the last click of Button, here is my code:
if (txtFile.createNewFile() || txtFile.isFile()) {
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(txtFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
BufferedWriter bwriter = new BufferedWriter(myOutWriter);
EditText desc__ = (EditText)findViewById(R.id.descriptionEditTExt);
try {
bwriter.newLine();
bwriter.write(lat+"|"+lng+"|"+desc__.getText().toString()+"|"+f+"|"+position);
bwriter.close();
myOutWriter.close();
fOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
/* handle directory here */
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please rewrite your FileOutputStream constructor as
FileOutputStream fos = new FileOutputStream(file, true);
here is suggests that your file will be opened in the append mode which will solve your first problem..
secondly if you want to add new line to the file use "\r\n" string
e.g. fos.write("\r\n".getBytes());
Hope this helps..
I have a function which writes exception logs in a file on SD CARD.But the problem is that it's writing only the first line of it, without any information about on which line is thrown that exception and etc. Any ideas how to get the whole Log?
Save to file :
public static void writeLogs(String text){
File logFile = new File("sdcard/Documents/Public/Log/crash_logs.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append("---START---");
buf.newLine();
buf.append(text);
buf.newLine();
buf.append("---END---");
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Invoke :
catch (Exception e) {
e.printStackTrace();
rpc.writeLogs(e.toString());
}
Any ideas?
e.toString doesn't provide the stack, try printStackTrace(writer or stream)
I had this problem too. I ended up splitting e.toString() by \n and then wrote each line individually to my log.
use println() instead of append.
PrintWriter p = new PrintWriter(new FileWriter("your text file.txt"));
p.println(text);