Working with files: read and write many times - android

I am newbie in Android development and I cant know that is going with files.
That's about audio information.
So, if I create new file and write in it, after it i read from this file.
And new iteration: I don't create new file (cuz i already got this file), and write in this file. Now I gonna read from file (after second write) that I can get from file?
I need get second written information, can I get it on this way?

yes, you have read again the file
let say you use a textfile to save your data.
Ex.
this is how i save it
File temf=new File(getCacheDir()+"/data/mytext.txt");
Writer out=null;
if(temf.exists()){
temf.delete();
}
try {
out = new BufferedWriter(new FileWriter(temf));
out.write("sample text") + "\r\n");
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
and this is how i retrieve it
FileInputStream fs;
try {
File temf=new File(getCacheDir()+"/data/mytext.txt");
if (temf.exists()) {
fs = new FileInputStream(temf);
DataInputStream dis = new DataInputStream(fs);
BufferedReader br = new BufferedReader(new InputStreamReader(
dis));
String str=br.readLine();
while(str!=null)
{
if(str=="text you want to compare"){
break;
}else{
str=br.readLine();
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Related

Android, Why Can't I Read the File I Just Wrote?

I am using the first snippet to write a file.
String fileName = "Test6.txt";
String outputString="Text for File";
try {
FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(outputString.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
And the second to read it.
try{
FileInputStream InputStream = openFileInput("Text6.txt");
InputStreamReader inputStreamReader = new InputStreamReader(InputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String lineData = bufferedReader.readLine();
}catch(FileNotFoundException ex)
{
Log.d(TAG, ex.getMessage());
}
catch(IOException ex) {
Log.d(TAG, ex.getMessage());
}
But I can't read it, I get:
java.io.FileNotFoundException: /data/user/0/com.example.android.buildingmarque2/files/Text6.txt (No such file or directory)
I can also get a list of the files and Test6.txt is in the list.
Also, Android Studio Device File Explorer shows it.
It could be a problem with the path.
Device Explorer, "Copy Path" gives me
/data/data/com.example.android.buildingmarque2/files/Test6.txt
But the Log says:
/data/user/0/com.example.android.buildingmarque2/files/Text6.txt
I'm confused?
Typo. One is "Text6" the other is "Test6". Use a constant for both names to avoid this in the future

Problems reading .txt file in Android

I am trying to read a file i download from Dropbox (using Dropbox CORE API).
private void downloadropboxfile(final String filename)
{
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
File file = new File(getCacheDir(),filename);
if(!file.exists())
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
DropboxAPI.DropboxFileInfo info=mDBApi.getFile("/" + filename, null, outputStream, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
Then in another function i call the downloaddropbox function and try to read the file content on Onclick event.
String filename = "info.txt";
downloadropboxfile(filename);
String strLine = "";
try {
InputStream instream = new FileInputStream(new File(getCacheDir(),filename));
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader bReader = new BufferedReader(inputreader);
/** Reading the contents of the file , line by line */
while ((strLine = bReader.readLine()) != null) {
mTestOutput.setText(strLine);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My problem is that i don't get the file content immediately. I need to click the button 3-4 times in order to read the file content. What's the problem with my code?
You're calling downloaddropboxfile, which starts a new thread to download the file. But then you're immediately trying to read the local file (before it's downloaded).
If you haven't worked with threading before, the important thing to understand is that downloaddropboxfile returns almost immediately, but the thread it starts keeps running in the background. You'll need to wait for it to finish before trying to do something with the downloaded file.

Data saving management in text file using java

I wrote an android application which collect data from sensors and saves the collected data in a text file for plotting and for other purpose after that,
the problem is to save the collected data in specific format into text file
for example: I need to save the data inside text file as following format:
1,34
2,40
3,56
4,66
.
.
.
... and so on.
But the data is stored with me as the following:
1,342 403 564 66
which this is the problem.
The writing function looks like this:
public void writing_in_file_1(){
try{
//file_1.createNewFile();
fw = new FileWriter(file_1, true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.append(String.valueOf(time + "\t "+currentReading ) );
out.append("\n");
//out.append(String.valueOf(current_reading_list));
out.flush();
Toast.makeText(
this,
"Done writing SD 'specific text file'",
Toast.LENGTH_SHORT)
.show();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can use a BufferedWriter.newLine() method here:
BufferedWriter buf = new BufferedWriter(new FileWriter(Filename, true));
buf.append(text);
buf.newLine();
buf.close();
Also, my guess is you don't really need the PrinterWriter class there.

What's wrong with my read and write of the file in Android app's assets?

Code first:
AssetManager mgr = DeviceListActivity.this.getApplicationContext().getAssets();
try {
Log.e("Glenn:", address);
FileOutputStream fout = mgr.openFd("device/device_address.txt").createOutputStream();
PrintWriter _fout = new PrintWriter(fout);
_fout.println(address);
Log.e("Glenn", address);
_fout.close();
fout.close();
InputStream fin = mgr.open("device/device_address.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
address = br.readLine();
try {
Log.e("Glenn:", address);
} catch (NullPointerException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
Log.e("Glenn", "error with OutputStream");
}
The value of address printed by the first two Log.e() calls is the right value, which actually is a device MAC address. However, when I was trying to test the value of address read from the file, which had just been written, NullPointerException has been caught within the Log.e() call. This means the value read from the file is NULL. Can anyone point out what's wrong with the code?
You cannot write in your app's asset file. You have only read but not write permissions. AssetManager only provides methods to read the files from your app's asset folder.

Save Internal File for Login

Hy!!
I have a login form in my app, but i want to save/restore the textfile internal in the app not on the internal phone memory.
Are there some code snippets?
I made a internal file saving/restoring but it don't work.
if (cb.isChecked())
{
File file = new File("/mmt/sdcard/login.skip");
Writer output = null;
try
{
output = new BufferedWriter(new FileWriter(file));
output.write(etuser.getText().toString()+ ";" + etpw.getText().toString());
output.close();
}
catch (Exception e) {
// TODO: handle exception
}
}
File file = new File("/mmt/sdcard/login.skip");
if(file.exists())
{ try
{
BufferedReader input = new BufferedReader(new FileReader(file));
while (( line = input.readLine()) != null){
line2 = line;
}
etuser.setText(line2.split(";")[0]);
etpw.setText(line2.split(";")[1]);
input.close();
}
catch (Exception e) {
// TODO: handle exception
}
}
Edit: See Internal Storage
Alternative,
Use SharedPreference It'll be Private to you're Application. And cannot be accessed otherwise. (For a non-rooted phone, atleast)

Categories

Resources