I am trying to write to a text file a list of names. It is written one line at a time and I have a class for Writing to File and Reading from it.
Here is the class:
package com.example.mobiledayoff;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.content.Context;
public class userListIO {
Context fileContext;
public userListIO(Context fileContext){
this.fileContext=fileContext;
}
public void writeItems(String fileName, String name){
final String ls = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer =
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
writer.write(name + ls);
} catch (Exception e){
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<CharSequence> readItems(String filename){
ArrayList<CharSequence> list = new ArrayList<CharSequence> ();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fileContext.getApplicationContext().openFileInput(filename)));
String line;
while((line = br.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
}
I use this class to write a line from user input (EditText) to the file. And then I read from file and Display contents of the file in another EditText. Here is how I do it:
public void addUser(View view){
EditText text = new EditText(this);
text = (EditText)findViewById(R.id.add_user_text);
String name = text.getText().toString();
String filename = "userList.txt";
userListIO messenger = new userListIO(this);
messenger.writeItems(filename, name);
text.setText("");
ArrayList<CharSequence> list = messenger.readItems(filename);
EditText editText = (EditText) findViewById(R.id.debug_text);
String info = "";
int count = 0;
for (CharSequence item: list){
info += item.toString();
count++;
}
info += "; there are " + count + " lines";
editText.setText(info);
}
My main problem is that it seems that file gets overwritten each time I write into it and so I always have 1 line. Do you guys know how to fix this? By fix I mean: How to append to the file if it already exists or create one if it doesn't exist.
Also I found out that after I close and reopen an app, the file does not exist. How to create and save a file, so that after closing and reopening I could still use the data stored there?
p.s. Read/Write was taken from here:
The best way to store user input data for later work
Change
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
to
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE | Context.MODE_APPEND)));
This will combine the MODE_PRIVATE flag aswell as the MODE_APPEND flag.
P.S. You should get away from opening and closing a stream everytime you write a line. This produces a lot of overhead and rather should you try to keep the stream opened until all your data has been processed.
Related
I've been getting the following error when I attempt to run an android application that inputs data from a text file.
"java.io.fileNotFoundException: /File.txt: open failed:ENOENT (No such file or directory)"
The file in question is in the Eclipse project folder.
I also tried putting it in the assets folder as well as several others.
Here is the code in question:
File file = new File("File.txt");
TestOutput = new ArrayList<String>();
String x = "";
try
{
Scanner scanner = new Scanner(file);
while (sc.hasNextLine())
{
x = sc.nextLine();
TestOutput.add(x);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
So far I have attempted to use a wrapper class to no avail, the code of which is below:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileGet
{
ArrayList<String> TestOutput = new ArrayList<String>();
public FileGet() {
}
public ArrayList<String> getFile() {
File file = new File("TestOutput.txt");
TestOutput = new ArrayList<String>();
try
{
Scanner scanner = new Scanner(file);
String x = "";
while (scanner.hasNextLine())
{
x = scanner.nextLine();
TestOutput.add(x);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return TestOutput;
}
}
That code works fine outside of the android application. Any advice/responses would be greatly appreciated.
Try this, the string named "line" is the string where all the TextFile is read.
Put the .txt file under /resources/raw folder.
InputStream is = getResources().openRawResource(R.raw.name_of_file);
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line = null;
try {
while ((line = r.readLine()) != null)
total.append(line);
} catch (IOException e) {
e.printStackTrace();
}
line = total.toString();
I'm using this code to save data to file and read data from the file:
public static void save(FileIO files) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
files.writeFile(".save")));
for (int i = 0; i < 20; i++) {
out.write(Integer.toString(scores[i]));
out.write("\n");
}
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}
public static void load(FileIO files) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
files.readFile(".save")));
for (int i = 0; i < 20; i++) {
scores[i] = Integer.parseInt(in.readLine());
}
} catch (IOException e) {
} catch (NumberFormatException e) {
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
FileIO.java
package com.avoidblocks.avoidblocks.framework;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.SharedPreferences;
public interface FileIO {
public InputStream readFile(String file) throws IOException;
public OutputStream writeFile(String file) throws IOException;
public InputStream readAsset(String file) throws IOException;
public SharedPreferences getSharedPref();
}
I'm calling save(FileIO files) and load(FileIO files) multiple times in an app and it works fine while I'm in an app, but when I exit the app and start the app again, all data is gone.
Does anyone know how to create that data remains saved even when I exit the app, so that I could restore the data when I start the app again?
Also, is this the right way to save data if I want that saved data is only visible to my app and that after uninstall, all saved data is erased?
EDIT-EDIT-EDIT:
ok its your FileIO files variable that looks like it is wrong,
what are you using to get that variable?
should be
context.openFileOutput(".save", Context.MODE_PRIVATE)
for save and
context.openFileInput(".save")
for load
and it should be FileOutputStream for save and FileInputStream for read instead of FileIO.
and when adding it to the stream just pass that in.
so in your code you should create the BufferedWriter like this:
out = new BufferedWriter(new OutputStreamWriter(
context.openFileOutput(".save", Context.MODE_PRIVATE)));
and create BufferedReader like this:
in = new BufferedReader(new InputStreamReader(
context.openFileInput(".save")));
==================EDIT: my testing code=================
Ok, I created an activity and made the following two methods and declared an array of ints:
public static int scores[] = {11,12,13,14,15};
public static void save(Context context) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
context.openFileOutput(".saveingTest", Context.MODE_PRIVATE)));
for (int i = 0; i < scores.length; i++) {
out.write(Integer.toString(scores[i]));
out.write("\n");
}
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}
public static void load(Context context) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
context.openFileInput(".saveingTest")));
for (int i = 0; i < scores.length; i++) {
Log.d("testingApp", "test: " + Integer.parseInt(in.readLine()));
// scores[i] = Integer.parseInt(in.readLine());
}
} catch (IOException e) {
} catch (NumberFormatException e) {
} finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
in my onCreate I have the following two lines of code:
save(this);
load(this);
to test I did the following:
commented out load in onCreate, ran the app, than I removed the comment on load and commented out save in onCreate and i changed the numbers in the scores variable(this is unnecessary but i did it anyway) and ran the app, the result was the int values in scores from the first time the app was run, inside the android log viewer window on eclipse. you can also have buttons that trigger save and load instead if you don't want to comment and run.
try it yourself, it should work, and make sure you are doing the same thing in your actual android app, if it still dose not work you are doing something else wrong and its not an issue with saving the file.
i am working on an image gallery app in which i am loading images from URL so i have saved some image URLs in a text file and i am trying to read URLs from text file to ArrayList<String> but i am not able to load images in my app.
i tried this: but not works images are not loading
package com.nostra13.example.universalimageloader;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class Constants {
public static List<String> LIST = new ArrayList<String>();
public void parseFile() {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("link.txt"));
while ((sCurrentLine = br.readLine()) != null) {
LIST.add(sCurrentLine);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static final String[] IMAGES = LIST.toArray(new String[LIST.size()]);
private Constants() {
}
public static class Config {
public static final boolean DEVELOPER_MODE = false;
}
public static class Extra {
public static final String IMAGES = "com.nostra13.example.universalimageloader.IMAGES";
public static final String IMAGE_POSITION = "com.nostra13.example.universalimageloader.IMAGE_POSITION";
}
}
but if i add URLs manually like this: it works.
public static final String[] IMAGES = new String[] {
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTybItEfE2Xu-Or72BHw8uZf19_mV2Kr8cuuU8kKYrVbeZPXIeX-Q",
};
but i want to add text from text file (sdcard/file.txt) instead of manually adding.
Well, did you try and use Log.d() to post the lines of text that is being read from the file?
My best guess is that it's not reading the text file correctly, or perhaps formatting it wrongly (missing spaces perhaps, so it thinks its 1 big string?)
Try with this code:
public void parseFile() {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"link.txt");
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(file));
while ((sCurrentLine = br.readLine()) != null) {
LIST.add(sCurrentLine);
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
The call to Environment.getExternalStorageDirectory() will return the path of SD card, and the path of declared variable file is relative to the root of SD card. If the file on a folder, you should declare:
File file = new File(sdcard,"data/com.myapplication.example/images/link.txt");
I am trying to set text in EditText by reading a file but app get closed every time. Can someone tell what's wrong with this code?
package com.example;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class EditNoteActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
String FILENAME = "note_file";
EditText text = (EditText) findViewById(R.id.editText1);
byte[] buffer = new byte[100];
super.onCreate(savedInstanceState);
setContentView(R.layout.editnote);
//Intent intent = getIntent();
FileInputStream fos = null;
try {
fos = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
assert fos != null;
try {
fos.read(buffer, 0, 10);
String str = buffer.toString();
text.setTextSize(48);
text.setText(str);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public void onClickSave(View theButton) {
//Intent intent = new Intent(this, MyActivity.class);
//startActivity(intent);
String FILENAME = "note_file";
EditText text = (EditText) findViewById(R.id.editText1);
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
assert fos != null;
try {
fos.write(text.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
finish();
}
public void onClickBack(View theButton) {
//Intent intent = new Intent(this, MyActivity.class);
//startActivity(intent);
finish();
}
}
I tried to edit this to remove irrelevant code but I got error, "Your post does not have much context to explain the code sections; please explain your scenario more clearly.". Unfortunately there is not much and anyway this question has been answered.
You are initializing EditText (text) before setting content view, so that the EditText object is null while finding edit text by id, that's why application crashed.
Modify your code as follows
super.onCreate(savedInstanceState);
setContentView(R.layout.editnote);
String FILENAME = "note_file";
EditText text = (EditText) findViewById(R.id.editText1);
byte[] buffer = new byte[100];
FYI: while asking questions, post error log too then only you can get quick and proper answers.
Update
Refer :
to get error log from eclipse
for converting byte array into string
byte[] bytes = {...}
String str = new String(bytes, "UTF8"); // for UTF8 encoding
this is the issue.
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>();