I have a custom saving method I'm using in a project. Each time I call the method, I'm looking to have the next entry inserted in a new line in a text file.
For example,
if I input "dog1" on the first method call
then input "dog2" on the next method call.
The output should be
dog1
dog2
Unfortunately dog2 overwrites dog1 so my text file output always contains a single entry.
Does anyone notice something off about my code?
Thanks!
public void save(String filename, String st,
Context ctx) {
ArrayList<String[]> list = new ArrayList<>();
list.add(new String[] {st});
FileOutputStream fos;
try {
fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
OutputStreamWriter os= new OutputStreamWriter(fos);
String t = st;
for(String[] arr: list){
for(String s: arr){
os.write(s);
}
os.write(System.getProperty( "line.separator" ));
}
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
File reader method
public String read(String filename, Context ctx){
String tr="";
FileInputStream fis = null;
try {
fis=ctx.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
StringBuilder sb= new StringBuilder();
String text;
while((text=br.readLine())!=null){
sb.append(text);
tr = sb.toString();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis!=null){
try{
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return tr;
}
Declare ArrayList globally or outside the save method.
Because every time on call save() method new object create for list and override previous data with new data instead of add new data on list.
Declare below line outside save() method or globally
ArrayList<String[]> list= new ArrayList<>();
Related
I'm writing a string to a file using the method saveData();
public void saveData(){
String fileName = "lifeClockSavedData";
String birthYear = "1986";
try {
FileOutputStream fileOutputStream = openFileOutput(fileName, MODE_PRIVATE);
fileOutputStream.write(birthYear.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And opening it in a widget activity using retrieve();
String messageString;
public void retrieve(Context context){
String fileName = "lifeClockSavedData";
try {
String message;
FileInputStream fileInputStream = context.getApplicationContext().openFileInput(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((message = bufferedReader.readLine())!=null);{stringBuffer.append(message);}
messageString = stringBuffer.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
As far as I can tell, this should set messageString to "1986", but the value is always "null".
I'd appreciate a pointer as to what's going wrong.
edit: This question isn't a duplicate of context.openFileInput() returning null when trying to access a stored file
as I'm not trying to get openFileInput() to accept a path
I'm writing a string to a file
No, you are not. You are writing bytes to file.
Either:
Write a string to the file (e.g., via a PrintWriter wrapped around an OutputStreamWriter), or
Read bytes from the file, then construct a String from those bytes
scrapped:
while ((message = bufferedReader.readLine())!=null);{stringBuffer.append(message);}
replaced with:
stringBuffer.append(bufferedReader.readLine());
Not sure why it worked, as bufferedReader.readline() wasn't null.
I'm new in Android dev and I want to ask this.
I've create an Android program that saves passwords in a txt file.
I want to retrieve these passwords and display them into a listView.
Below is the code that I wrote to save passwords to my file:
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_APPEND);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textView3.getText().toString()+"\n");
outputWriter.close();
//display password saved message
Toast.makeText(getBaseContext(), "Password saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Now this is my code that reads the file:
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textView4.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
I want to know if there is a way to display these passwords into a listView.
Namely I'm looking for the code. I appreciate any help.
:NOTE: If that question is already answered, I'm sorry.
SOLUTION
Thanks to #mehd-azizi I finally found the solution to my problem.
change the read part to this :
public String[] readFileAsString(String fileName) {
Context context = this;
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
ArrayList<String> list=new ArrayList<String>();
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) {
list.add(line);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
String[] stockArr = new String[list.size()];
return list.toArray(stockArr);
}
and use that like this to read the file and fill the ListView:
ListView listView=(ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter=new ArrayAdapter<String(getApplicationContext(),android.R.layout.simple_list_item_1,readFileAsString("mytextfile.txt"));
listView.setAdapter(adapter);
change the read part to this :
public String[] readFileAsString(String fileName) {
Context context = this;
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
ArrayList<String> list=new ArrayList<String>();
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) {
list.add(line);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
String[] stockArr = new String[list.size()];
return list.toArray(stockArr);
}
and use that like this to read the file and fill the ListView:
ListView listView=(ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1,
readFileAsString("mytextfile.txt"));
listView.setAdapter(adapter);
I have a arrays of apk files, what I need is to do write the apk files of ArrayList into cache storage and read it back again as same ArrayList. I know how to insert a single file and retrieve back again from the cache. But whereas ArrayList objects as concern I completely stuck up with the solutions and methodology. Please help me. I am using following code for read and write into cache memory. Any modification or slight changes in my code will be more helpful to me. Thanks in advance
Actual code for Read and write single File
//Write to cache dir
FileWriter writer = null;
try {
writer = new FileWriter(tmpFile);
writer.write(text.toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
//Read to cache directory
String TMP_FILE_NAME = "base.apk";
File tmpFile;
File cacheDir = getBaseContext().getCacheDir();
tmpFile = new File(cacheDir.getPath() + "/" + TMP_FILE_NAME) ;
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tmpFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
Modified code for my requirement to insert ArrayList<File>
String tempFile = null;
public void writeFile(ArrayList<File> files(){
for(File file: files) {
FileWriter writer = null;
try {
writer = new FileWriter(file);
tempFile = file.getName().toString();
writer.write(file.getName().toString());
writer.close();
// path to file
// tmpFile.getPath()
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is where I stuck completely to read as ArrayList
What i tried is
String line="";
StringBuilder text = new StringBuilder();
try {
FileReader fReader = new FileReader(tempFile);
BufferedReader bReader = new BufferedReader(fReader);
while( (line=bReader.readLine()) != null ){
text.append(line+"\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
I found my own answer for my question after a longstruggle from the blog.
To Write a ArrayList<File>:
public static void createCachedFile (Context context, String key, ArrayList<File> fileName) throws IOException {
String tempFile = null;
for (File file : fileName) {
FileOutputStream fos = context.openFileOutput (key, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream (fos);
oos.writeObject (fileName);
oos.close ();
fos.close ();
}
}
To Read a ArrayList<File>
public static Object readCachedFile (Context context, String key) throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput (key);
ObjectInputStream ois = new ObjectInputStream (fis);
Object object = ois.readObject ();
return object;
}
Final code in my Activity
createCachedFile (MainActivity.this,"apk",adapter.getAppList ());
ArrayList<File> apkCacheList = (ArrayList<File>)readCachedFile (MainActivity.this, "apk");
i'm trying to save a list of integers in my application by saving each integer in a new line of a file in the internal storage.
For retreiving it I read it line by line and put every linevalue, parsed as integer, in my list of integers.
I know a database is better for this kinda stuff, but this should work.
I am trying for quite a while now, but it never seems to work. I always get a nullpointerexception when trying to read. I logged "line", it gave the value it should have. But
saving one id, adding it as a new string:
private void saveToFavorites(Integer saveFav) {
String favstr = String.valueOf(saveFav);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("favorites", MODE_WORLD_WRITEABLE)));
writer.newLine();
writer.append((favstr));
System.out.println(" added to favs :"+ saveFav);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And the reading method:
#SuppressWarnings("null")
private List<Integer> readFileFromInternalStorage() {
List<Integer> favs = null;
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(openFileInput("favorites")));
String line;
while ((line = input.readLine()) != null) {
System.out.println("readFileFromInternalStorage line value: "+ line );
favs.add(Integer.parseInt(line));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("readFileFromInternalStorage: fail" );
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return favs;
}
Which is in an other activity. I thought it would work but it clearly doesnt. When reading back, the logline: System.out.println("readFileFromInternalStorage line value: "+ line );
displays that the value of line equals the LAST added id,and an empty line, and not the others too. So the line by line saving fails. Also when parsing it to an integer it fails, what is weird because it is only a number.
08-01 12:29:54.190: I/System.out(1540): readFileFromInternalStorage line value:
08-01 12:29:54.190: I/System.out(1540): readFileFromInternalStorage line value: 301
Anyone knows what i need to change?
Since Integer is Serializable I sugget to serialize the entire List:
private void saveList(List<Integer> list) {
try {
File file = Environment.getExternalStorageDirectory();
File filename = new File(file, "yourfilename");
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void readList()
{
try {
File file = Environment.getExternalStorageDirectory();
File filename = new File(file, "yourfilename");
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
List<Integer> list= (List<Integer>) in.readObject();
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
try this May it help you :-
1 - String saveFav = contaains all integer this form I1+"/"I2+"/"I3;
2:- then save it into file
private void saveToFavorites(String saveFav) {
//right here your code for write into file saveFave string
}
in reading file read string and split("/").it's working for me .
Here's some working code that will read and write ints to the phones internal memory.
You can create an array or list of ints and basically just iterate over it until all ints are saved/read to/from the memory:
Here's the code to write an int to the memory:
public void writePrimitiveInternalMemory(String filename, int value) {
SharedPreferences preferences = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(filename, value);
editor.commit();
}
Here's code to read from the memory:
public int readPrimitiveInternalMemoryInteger(String filename) {
SharedPreferences preferences = this.getPreferences(Activity.MODE_PRIVATE);
return preferences.getInt(filename, 0);
}
I hope this helps you!
You are not allocating the integer list...
List<Integer> favs = null;
Allocate a new arraylist..
List<Integer> favs = new ArrayList<Integer>();
I'm creating a class to manage text files. I have a method to write and an other to read my file :
public static void writeFiles(Context context, String nomFichier, String content, char mode) {
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
if (mode == 'd') {
context.deleteFile(nomFichier);
} else {
fOut = context.openFileOutput(nomFichier, Context.MODE_APPEND);
osw = new OutputStreamWriter(fOut);
osw.write(content);
osw.flush();
}
} catch (Exception e) {
Toast.makeText(context, "Message not saved",Toast.LENGTH_SHORT).show();
} finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
Toast.makeText(context, "Message not saved",Toast.LENGTH_SHORT).show();
}
}
}
When I create a file, it is filled with few empty lines. I want to set the content of my file into an EditText, so I don't want the blanks.
How can I create a file without blanks?
Thx, korax.
EDIT :
I use trim(), suggested by appserv and acj, but in the read function instead of write function. It works fine, thx you!
public static String readFile(Context context, String fileName) {
FileInputStream fIn = null;
InputStreamReader isr = null;
char[] inputBuffer = new char[255];
String content = null;
try {
fIn = context.openFileInput(fileName);
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
content = new String(inputBuffer);
} catch (Exception e) {
//Toast.makeText(context, "Message not read",Toast.LENGTH_SHORT).show();
}
finally {
try {
isr.close();
fIn.close();
} catch (IOException e) {
//Toast.makeText(context, "Message not read",Toast.LENGTH_SHORT).show();
}
}
return content.trim();
}
If you are using a text editor to create the file, the editor may be adding some blank lines to pad the file size. You could call openFileOutput without the MODE_APPEND flag to create the new (empty) file programmatically, thus avoiding the text editor.
Otherwise, appserv's suggestion to use trim() should work nicely to clean up the string.