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
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 am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.
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
I have an application consist on reading AND saving an xml file and to write it if internet connection is available,else it will read the file already saved on the terminal.
WriteFeed function:
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
WriteFeed function:
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
I have enough diskSpace ,sometimes i get "MemoryCach will use up to 16 Mb" ,always i get "Not enough disk space,will not index" and "FeatureCode > cannot open file"
whats wrong in my app?
I am working on an application in which I have a some text in English and Arabic. For the sake of example I can say it as a words meaning application. The word is in English and user will get it's meaning in Arabic.
For Example:
Test اختبار // Test is the word and then there is it's meaning in Arabic
But when I read this local file I don't get Arabic as intended. Instead I get some strange characters. I am making sure that file is UTF-8 encoded and when I read the file I again pass encoding scheme to be UTF-8..but it does not wwork. Code snippet is as follows:
InputStream inputStream = resources.openRawResource(R.raw.textfile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
try {
String line;
while((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, " ");
if (strings.length < 2) continue;
addWord(strings[0].trim(), strings[1].trim());
}
} finally {
reader.close();
}
Any help is appreciated..Thanks..!!!
I actually built an helper class that handles FileIO (and is completely compatible with Hebrew) so I guess Arabic will be no problem:
/***
*
* #author Android Joker ©
* Do NOT copy without confirmation!
* Thanks!
*
*/
public class FileMethods {
private Boolean isOk;
private Context mContext;
private String fileName;
public FileMethods(Context c, String FILENAME) {
this.isOk = true;
this.mContext = c;
this.fileName = FILENAME;
}
public void reWrite(Object DATA) {
//For deleting the content of the file and then writing
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
fos.write(DATA.toString().getBytes());
fos.close();
Log.i("File Writing ("+this.fileName+")", "Success!");
isOk = true;
}
catch (IOException e) {
e.printStackTrace();
Log.e("File Writing ("+this.fileName+")", "Failed!");
isOk = false;
}
}
public void Write(Object DATA) {
//For keeping the previous contents and continue writing
String data = Read("") + DATA.toString() + "\n";
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
Log.i("File Writing ("+this.fileName+")", "Success!");
isOk = true;
}
catch (IOException e) {
e.printStackTrace();
Log.e("File Writing ("+this.fileName+")", "Failed!");
isOk = false;
}
}
public void Clear() {
//For deleting all the file contents
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
fos.write("".getBytes());
fos.close();
Log.i("Cleared"+"("+this.fileName+")", "Success!");
isOk = true;
}
catch (IOException e) {
e.printStackTrace();
Log.e("Cleared"+"("+this.fileName+")", "Failed!");
isOk = false;
}
}
public String Read(String inCaseOfFailure) {
//For reading (If reading failed for any reason, inCaseOfFailure will be written)
String info = "";
try {
FileInputStream fis = mContext.openFileInput(this.fileName);
byte[] dataArray = new byte[fis.available()];
if (dataArray.length>0) {
while(fis.read(dataArray)!=-1)
{
info = new String(dataArray);
}
fis.close();
Log.i("File Reading ("+this.fileName+")","Success!");
isOk = true;
}
else {
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
fos.write(inCaseOfFailure.getBytes());
fos.close();
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Success!");
isOk = true;
}
catch (Exception e) {
e.printStackTrace();
isOk = false;
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Failed!");
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "MOVING ON");
}
}
}
catch (FileNotFoundException e) {
try {
FileOutputStream fos = mContext.openFileOutput(this.fileName, Context.MODE_PRIVATE);
if (inCaseOfFailure != null) {
fos.write(inCaseOfFailure.getBytes());
fos.close();
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Success!");
isOk = true;
}
else {
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Failed!");
isOk = false;
}
}
catch (IOException e1) {
e.printStackTrace();
Log.e("File Writing In Case Of Failure ("+this.fileName+")", "Failed!");
isOk = false;
}
}
catch (IOException e) {
e.printStackTrace();
Log.e("File Reading ("+this.fileName+")", "Failed!");
isOk = false;
}
return info;
}
public Boolean GetIsOK() {
//Method that checks whether the FileIO was successfully running or not
Boolean temp = isOk;
isOk = true;
return temp;
}
}
Each instance of the class handles another file (FILENAME).
Hope this helps!