I want to save my data in a .txt file. In another activity I want to be able to read the saved data. I want to save multible values each time and put them together on a line, the next values need to be in a new line. I tried \n System.getProperty("line.separator"); System.lineSeparator(); and \n\r to start in a new line but this doesn't seem to work while the data still end up behind each other instead of being on another line.
I use this code to write to the file:
Context context = getApplicationContext();
writedatatofile(context);
protected void writedatatofile(Context context){
try
{
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("data_log.txt", Context.MODE_APPEND));
String data;
if (newstart){
data = "Exersice started \n" + "t.s a.s t.a a.a cnst";
} else {
data = (Integer.toString(time_step)+Integer.toString(new_average_step)+Integer.toString(time_footaid)+Integer.toString(new_average_aid)+Boolean.toString(rhythmconsistent)+"\n");
}
outputStreamWriter.append(data);
outputStreamWriter.close();
Toast.makeText(this, "Data has been written to File", Toast.LENGTH_SHORT).show();
}
catch(IOException e) {
e.printStackTrace();
}
}
and this code to read the file:
Context context = getApplicationContext();
String fileData = readFromFile(context, fileName);
TextView datalog = findViewById(R.id.datalog);
datalog.setText(fileData);
private String readFromFile(Context context, String fileName){
String ret = " ";
try {
InputStream inputStream = context.openFileInput(fileName);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
Toast.makeText(this, "Data received", Toast.LENGTH_SHORT).show();
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
} else {
Toast.makeText(this, "No data received", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e){
Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
} catch (IOException e){
Toast.makeText(this, "Can not read file", Toast.LENGTH_SHORT).show();
}
return ret;
}
As mentioned "\n" doesn't solve the problem but is also doesn't show up in my dataas \n. So it is not stored as a normal String.
When you write the file:
BufferedWriter writer = new BufferedWriter(outputStreamWriter);
writer.write(data);
writer.newLine(); // <-- this is the magic
writer.close();
You can read the data from .txt file using below code.
File exportDir = new File(Environment.getExternalStorageDirectory(), File.separator + "bluetooth/abc.txt");
if (exportDir.exists()) {
FileReader file = null;
try {
file = new FileReader(exportDir);
BufferedReader buffer = new BufferedReader(file);
String line = "";
int iteration = 0;
while ((line = buffer.readLine()) != null) { //read next line
if (iteration == 0) { //Skip the 1st position(header)
iteration++;
continue;
}
StringBuilder sb = new StringBuilder();
String[] str = line.split(",");
//get the single data from column
String text1 = str[1].replace("\"", "");
String text2 = str[2].replace("\"", "");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Related
I am currently encountering a problem saving a text file on the internal storage.
The problem is that whenever i exit the application, the file seems to be deleted.
I wrote this method that is called at the start of the application, to create a blank text file :
private void init() {
String FILE_NAME = "save.txt";
try {
new BufferedWriter(new FileWriter(getFilesDir() + FILE_NAME));
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
this function is called to read all lines written in it :
private List<String> readFromFile() {
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = new FileInputStream(getFilesDir()+"save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
return ret;
}
And finaly this method is called to append a string in the text file if it's not already in it :
private void save(String unNom) {
String FILE_NAME = "save.txt";
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = new FileInputStream(getFilesDir()+"save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
if(!ret.contains(unNom)){
ret.add(unNom);
}
bReader.close();
FileOutputStream fos = new FileOutputStream(getFilesDir() +FILE_NAME);
for (String ligne: ret) {
ligne+="\n";
fos.write(ligne.toString().getBytes());
}
fos.flush();
fos.close();
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
What should I do to save correctly the file in the internal storage ?
Sorry for my bad english,
Thank you for your help !
The init was'nt necessary. I removed the method and I edited the save method, so it could create a new file if a not found exception was raised :
private void save(String unNom) {
String FILE_NAME = "save.txt";
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = openFileInput("save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
if (!ret.contains(unNom)) {
ret.add(unNom);
}
bReader.close();
FileOutputStream fos = null;
fos = openFileOutput("save.txt", this.MODE_PRIVATE);
for (String ligne : ret) {
ligne = "\n" + ligne;
fos.write(ligne.getBytes());
}
fos.close();
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
try {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
FileOutputStream fos = null;
fos = openFileOutput("save.txt", this.MODE_PRIVATE);
fos.write(unNom.getBytes());
fos.close();
Toast.makeText(this, "NEW FILE", Toast.LENGTH_LONG).show();
}
catch(Exception e2){}
}
}
I want to read XML file, save it as String and pass to setText. I don't want to parse it but see it on my smartphone screen with all tags and white-characters, eg.
<a>
<b>some text</b>
</a>
not:
some text
How to do it?
FYI, this is how I solve my problem:
public String readXML() {
String line;
StringBuilder total = new StringBuilder();
try {
InputStream is = activity.getAssets().open("subjects.xml");
BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
total = new StringBuilder();
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return total.toString();
}
Use FileInputStream to read file:
File file = new File(<FilePath>);
if (!file.exists()) {
System.out.println("File does not exist.");
return;
}
if (!(file.isFile() && file.canRead())) {
System.out.println(file.getName() + " cannot be read from.");
return;
}
try {
FileInputStream stream = new FileInputStream(file);
char current;
while (stream.available() > 0) {
current = (char) stream.read();
//Do something with character
}
} catch (IOException e) {
e.printStackTrace();
}
I have been working on this for a while and I am about to pull my hair out!!
If I use this...
public void readFile() {
BufferedReader buffReader = null;
StringBuilder result = new StringBuilder();
try {
FileInputStream fileIn = openFileInput("VariableStore.txt");
buffReader = new BufferedReader(new InputStreamReader(fileIn));
String line;
while ((line = buffReader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert buffReader != null;
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String resultString = result.toString();
String[] controlString = resultString.split("$");
// String wb = controlString[4];
// String sb = controlString[5];
((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
// ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
}
The Button.setText works fine with "resultString" or with "result" which is a string I have input formatted as xxx$xxx$xxx$xxx$xxx so when I read it back in with the readFile() I want to use .Split and put it into an array "controlString" and then assign the array elements to my widgets i.e. setText(controlString[0]); but if I so much as even uncomment the lines String wb = controlString[4]; or String sb = controlString[5]; my program crashes. Why wont the array elemts work here?
Here is my writeFile().... (Which works perfectly.
public void writeFile() {
BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();
String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;
try {
FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
try {
buffWriter.write(writeString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
assert buffWriter != null;
buffWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found the problem...
Instead of this:
String[] controlString = resultString.split("$");
I had to use this:
String[] controlString = resultString.split(Pattern.quote("$"));
I want to read a text file that i had write in another activity using OutputStreamWriter.
this is my readFromFile method in Sale.java:
private int readFromFile(String request) {
int res = 0;
try {
//InputStream inputStream = openFileInput("dalassnums.txt");
File file=new File("dalassnums.txt");
InputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null ) {
String s=bufferedReader.readLine();
if(receiveString==request) {
res=Integer.valueOf(s);
break;
}
}
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
res=0;
} catch (IOException e) {
//Log.e("login activity", "Can not read file: " + e.toString());
}
return res;
}
And this is writeToFile method in MainActivity.java:
private void writeToFile2(String numchar) {
try {
//File file=new File("dalassnums.txt");
//OutputStream outputStream=new FileOutputStream(file);
OutputStreamWriter outputStreamWriter;
if(numchar=="1") outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_PRIVATE));
else outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_APPEND));
for(int k=0; k<imageNums.size();k+=2){
outputStreamWriter.append(imageNums.get(k));
outputStreamWriter.append("\n");
outputStreamWriter.append(imageNums.get(k+1));
outputStreamWriter.append("\n");
}
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
When performing readFromFile, it returns 0 that means file not found;
I read about passing context but i don't know what context to pass; And wondering if there is any other way than passing context.
Any help would be appreciated.
Use : openFileInput in readFromFile, look here for example:
openFileInput() and/or openFileOutput() i/o streams silently failing
Another problem is that this is invalid:
if(numchar=="1")
you should
if(numchar.equals("1"))
otherwise you compare reference values instead content of string
I have an utility class named 'MyClass'. The class has two methods to read/write some data into phone's internal memory. I am new to android, Please follow below code.
public class MyClass {
public void ConfWrite() {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
while executing ConfWrite method, it fails
please provide a better solution to solve this
thanks in advance
You can Read/ Write your File in data/data/package_name/files Folder by,
To Write
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
To Read
BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(getFilesDir()+File.separator+"MyFile.txt")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = bufferedReader.readLine()) != null){
builder.append(read);
}
Log.d("Output", builder.toString());
bufferedReader.close();
public static void WriteFile(String strWrite) {
String strFileName = "Agilanbu.txt"; // file name
File myFile = new File("sdcard/Agilanbu"); // file path
if (!myFile.exists()) { // directory is exist or not
myFile.mkdirs(); // if not create new
Log.e("DataStoreSD 0 ", myFile.toString());
} else {
myFile = new File("sdcard/Agilanbu");
Log.e("DataStoreSD 1 ", myFile.toString());
}
try {
File Notefile = new File(myFile, strFileName);
FileWriter writer = new FileWriter(Notefile); // set file path & name to write
writer.append("\n" + strWrite + "\n"); // write string
writer.flush();
writer.close();
Log.e("DataStoreSD 2 ", myFile.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readfile(File myFile, String strFileName) {
String line = null;
try {
FileInputStream fileInputStream = new FileInputStream(new File(myFile + "/" + strFileName)); // set file path & name to read
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // create input steam reader
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) { // read line by line
stringBuilder.append(line + System.getProperty("line.separator")); // append the readed text line by line
}
fileInputStream.close();
line = stringBuilder.toString(); // finially the whole date into an single string
bufferedReader.close();
Log.e("DataStoreSD 3.1 ", line);
} catch (FileNotFoundException ex) {
Log.e("DataStoreSD 3.2 ", ex.getMessage());
} catch (IOException ex) {
Log.e("DataStoreSD 3.3 ", ex.getMessage());
}
return line;
}
use this code to write --- WriteFile(json); // json is a string type
use this code to read --- File myFile = new File("sdcard/Agilanbu");
String strObj = readfile(myFile, "Agilanbu.txt");
// you can put it in seperate class and just call it where ever you need.(for that only its in static)
// happie coding :)