openFileInput always returning null - android

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.

Related

Previous entry overwriting old entry with custom save method

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<>();

Android where file is saved FileOutputStream

Here how I write bytes to a file. I'm using FileOutputStream
private final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
byte[] readBuffer = (byte[]) msg.obj;
FileOutputStream out = null;
try {
out = new FileOutputStream("myFile.xml");
out.write(readBuffer);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and now I want to open that file, so I need to have path of that file. So how I need to open that file?
EDIT:
Here how I read from file, but I can't see anything...
BufferedReader reader = null;
FileInputStream s = null;
try {
s = new FileInputStream("mano.xml");
reader = new BufferedReader(new InputStreamReader(s));
String line = reader.readLine();
Log.d(getTag(), line);
while (line != null) {
Log.d(getTag(), line);
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I recommend to use this for writting:
OutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourfilename");
So to read the location:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+transaction.getUniqueId()+".pdf");
To read the path:
file.getAbsolutePath();
Your file is save in path /Data/Data/Your package Name/files/myFile.xml
you can use this.getFileDir() method to get the path of the files folder on the Application.
So use this.getFileDir() + "myFile.xml" to read the file.
How it is reported inside the developers guide you have to specify where you want to save your file. You can choose between:
Saving the file in the internal storage:
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Or on second instance you could save your file in external storage:
// Checks if external storage is available to at least read
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
Just remember to set permissions!!!!
Here there is the entire documentation: Documentation

Writing and Reading ArrayList<File> into android cache memory

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");

write into a file and read it to save the content into a variable like String

firstly, i search an answer everywhere but i didn't found.
Thank you very much for your answers.
In fact, i try to write into a file. Then, i try to save the content into a StringBuffer. And finally i try to show it via a TextView, but it shows nothing!
public class MainActivity extends Activity {
String finall;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos;
try
{
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
FileInputStream in = null;
try
{
in = openFileInput("hello_file.txt");
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while(in.read(buffer) != -1)
{
fileContent.append(new String(buffer));
}
finall = fileContent.toString();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
TextView text = (TextView)findViewById(R.id.mehmet);
text.setText(finall);
}
}
Try closing your FileInputStream after the read is finished as you did with FileOutputStream. This makes the data get flushed.
As said by #Piovezan you should close your file, but you should also consider that the intended valued returned by in.read(buffer) may not be equal to buffer.length
So you could have some dirty values at the end. And I don't know if this is your case but StringBuffer is thread safe, so if you aren't working in a multi thread section of your app you could switch to StringBuilder for better performance and less overhead

Using InputStream to read file from internal storage

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;
}
}

Categories

Resources