I am writing to file in android and read from the same file using the below code:
//Write data on file
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
fOut = openFileOutput("gasettings.dat", MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, "Settings saved", Toast.LENGTH_SHORT)
.show();
}
catch (Exception e) {
e.printStackTrace();
}
and the code for reading from file is:
InputStreamReader isr = null;
fileInputStream fIn = null;
char[] inputBuffer = new char[255];
String data = null;
try {
fIn = openFileInput("gasettings.dat");
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
}
catch (Exception e) {
e.printStackTrace();
}
as per now I am only able to save a string to this file.
I like to write a DATE array to it and also want to read back the data as array.
I know that the return type of read method will be changed, but I am not getting the idea of how to read and write the DATE array or any other array to the file.
Thanks
In that case, your better choice is using JSON. It will allow you to save an array in String format, read it back and convert it again into the original array.
Take a look of this example: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
Related
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");
Essentially, what I'm trying to do is save an ArrayList of Strings in one activity and then read them in another. The file is created (I can see it in the DDMS) but for some reason I can't get the activity to read the objects.
Here's the reading code:
try {
FileInputStream fis = new FileInputStream("purchased_songs.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
purchasedSongs = (ArrayList<String>) ois.readObject();
ois.close();
for(int i=0;i<purchasedSongs.size();i++)
Log.d("purchased songs",purchasedSongs.get(i));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And here's the writing code:
try {
FileOutputStream fos = openFileOutput("purchased_songs.obj",MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(purchasedSongs);
os.close();
}catch(Exception e){
e.printStackTrace();
}
Of course I figured out what is wrong.
Change
FileInputStream fis = new FileInputStream("purchased_songs.obj");
to
FileInputStream fis = openFileInput("purchased_songs.obj");
I've searched for a couple days, and all I find is using bufferedReader to read from a file on internal storage. Is it not possible to use InputStream to read from a file on internal storage?
private void dailyInput()
{
InputStream in;
in = this.getAsset().open("file.txt");
Scanner input = new Scanner(new InputStreamReader(in));
in.close();
}
I use this now with input.next() to search my file for the data that I need. It all works fine, but I would like to save new files to internal storage and read from them without changing everything to bufferedReader. Is this possible or do I need to bite the bullet and change everything? FYI I don't need to write, only read.
To write a file.
String FILENAME = "file.txt";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
to read
void OpenFileDialog(String file) {
//Read file in Internal Storage
FileInputStream fis;
String content = "";
try {
fis = openFileInput(file);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {
}
content += new String(input);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
content will Contain your File Data.
You may try following code when you face a condition to read a file from a subfolder in internal storage. Sometimes you may get problems with openFileInput whey you trying to passing context.
here is the function.
public String getDataFromFile(File file){
StringBuilder data= new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String singleLine;
while ((singleLine= br.readLine()) != null) {
data.append(singleLine);
data.append('\n');
}
br.close();
return data.toString();
}
catch (IOException e) {
return ""+e;
}
}
I use the following code to save password in a txt file:
String FILE_NAME="lol.txt";
public void writeData(String password){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(password);
osw.close();
fOut.close();
}catch(Exception e){
e.printStackTrace(System.err);
}
}
but When I retrive the password that I just Saved using toast its appears OK, but when I Log it into my LogCat I got Something like the following:
gana???????????????????????????????????? .... and more four lines.
I save the word gana into my file using save method which work as OnClikc method that set value of EditText as password as below:
public void save(View v){
password= txt.getText().toString();
writeData(password);
}
any Way or clue how can I solve this problem?
regards
Use below code to reading file
byte[] b = null;
try
{
//read file data...
FileInputStream myFile = openFileInput("lol.txt");
b = new byte[1024];
myFile.read(b);
Log.i("Pass", "File data is: " + new String(b).trim());
myFile.close();
}
catch (IOException e)
{
}
only difference with your code is that i am using new String(b).trim() to remove blank space.
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.