I am trying to get a simple Hello World txt file to be written then read by my android application. When viewing the DDMS File Explorer it successfully creates the text file but i then get a FileNotFoundException when trying to read it.
try {
final String TESTSTRING = new String("Hello World");
FileOutputStream fOut = openFileOutput("test.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(TESTSTRING);
osw.flush();
osw.close();
FileInputStream fIn = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[TESTSTRING.length()];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
boolean isTheSame = TESTSTRING.equals(readString);
Log.i("File Reading Stuff", "success = " + isTheSame);
} catch (IOException e) {
e.printStackTrace();
}
also the error is java.io FileNotFoundException: /test.txt (No such file or directory)
Any Help Thanks.
I don't know where openFileOutput saves its files, but wouldn't you use it's input equivalent openFileInput to read such a file?
See my previous post with information about how to read/write to the external storage directory in Android:
Android how to use Environment.getExternalStorageDirectory()
-- Dan
Related
This question already has answers here:
How to create text file and insert data to that file on Android
(5 answers)
Closed 4 years ago.
how to write a text file in a public storage that it was visible for other apps. i.e. file manager.
what is wrong with my code.
String filename = "kontaktebi123.vcf";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
PrintWriter osw = new PrintWriter(outputStream);
ArrayList<String> nomrebi = numberGenerator(view);
osw.printf("blablabla")
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
}
You have to write the file in public directory like Document, Download or others.
String fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = "kontaktebi123.vcf";
File file = new File(fileDir + "/" + fileName);
Now write in the file and it will be visible to other apps.
try{
FileOutputStream fileOutStream = openFileOutput(fileName.txt",MODE_PRIVATE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileOutStream);
outputWriter.write("write your text here");
outputWriter.close();
Toast.maketext(context,"File Saved Successfully",Toast.LENGTH_SHORT).show();
}catch(Exception e){
e.printStackTrace();
}
I am using print writer and fileoutputstream to write a file in android async task using following function:
public static void saveFileToExternalMemoryAsync(Context context,String fileName, String json)throws Exception{
File AppPath = new File(Environment.getExternalStorageDirectory() + "/PDMA/DMAPPOutputs/");
if (!AppPath.exists()) {
AppPath.mkdirs();
}
File outputFile = new File(AppPath.getAbsolutePath() + "/" + fileName + ".dmapp");
if (!outputFile.exists())
outputFile.createNewFile();
MediaScannerConnection.scanFile(context, new String[] {AppPath.toString(),outputFile.toString()}, null, null);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile, true);
PrintWriter pw = new PrintWriter(fileOutputStream);
try{
pw.println(json);
pw.flush();
pw.close();
fileOutputStream.flush();
fileOutputStream.close();
}catch (Exception e){
e.printStackTrace();
}finally{
pw.flush();
pw.close();
fileOutputStream.flush();
fileOutputStream.close();
MediaScannerConnection.scanFile(context, new String[] {AppPath.toString(),outputFile.toString()}, null, null);
}
}
problem is that when I try to copy this file by connecting mobile to pc in mtp, its not copied fully. If I right click to see its size, its less than actual. Now If in android, I copy and paste this file somewhere else, say in downloads folder, size is correct and file is also complete.
What can be the problem.
UPDATE:
If I use fileOutputStream to write bytes one by one , then file is generated but I have to close application to access this file from pc.
Well it turns out that by adding this.cancel(true) at the end of onPostExecute() solved problem in my case.
I have a text file in folder res/raw name "pass.txt" and some data in it i want to delete this data and enter new data in it.... is it possible to write data on it?? otherwise what is correct path to store my text file so i can easily read/write data on it.... and what is the code to read and write data from it?? below is the code through which i can only read data from this text file
InputStream fr = getResources().openRawResource(R.raw.pass);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
String s=br.readLine().toString().trim();
Resources contained in your raw directory in your project will be packaged inside your APK and will not be writeable at runtime.
Look at Internal or External Data Storage APIs to read write files.
https://developer.android.com/training/basics/data-storage/files.html
you can use Android internal storage to Read and write file ... as res/raw is only Read only..you can not change content at runtime.
Here is the code:
Create file
String MY_FILE_NAME = “mytextfile.txt”;
// Create a new output file stream
FileOutputStream fileos = openFileOutput(MY_FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fileis = openFileInput(My_FILE_NAME);
Read from file:
public void Read(){
static final int READ_BLOCK_SIZE = 100;
try {
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) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Write to file:
public void Write(){
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write("TEST STRING..");
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
I am writing the data to the file in an external storage (SD card) on my android. The issue that I am facing is that it just makes one entry and does not go beyond that. I have looked up a number of Q/As here. Could someone please point me in the write direction? TIA!
FileOutputStream outputstream;
try {
file1 = new File(Environment.getExternalStorageDirectory(), "MyData.txt");
outputstream = new FileOutputStream(file1);
OutputStreamWriter oswriter = new OutputStreamWriter(outputstream);
BufferedWriter bwriter = new BufferedWriter (oswriter);
bwriter.append(entry);
bwriter.newLine();
bwriter.close();
outputstream.close();
} catch (Exception e) {
e.printStackTrace();
}
You have to tell FileOutputStream to append the data. By default it just overwrites all contents there. For this you only need to use a different constructor FileOutputStream(File, boolean):
outputstream = new FileOutputStream(file1, true);
I made this code to write on a sdcard, now how can I transform it to write into the internal memory ?
//private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/liste.txt"; Path used to write on sdcard
try{
File file = new File(path);
BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
bw.write("something");
bw.flush();
bw.close();
catch(Exception e) {...}
In android each application has its own folder under /data/data/package/
this dir is only accessable by your app and the root if the device is rooted
to access this dir and read/write to it, you can use:
getApplicationContext().openFileOutput(name, mode);
and
getApplicationContext().openFileInput(name);
more about this here : Docs
USe this code:
FileOutputStream fos;
fos = context.openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(data.getBytes()); //write to application top level directory for immediate sending
fos.close();
try{
File file = new File("/data/data/com.example.packagename/files/");
BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
bw.write("something");
bw.flush();
bw.close();
catch(Exception e) {...}
or
//To read file from internal phone memory
//get your application context:
Context context = getApplicationContext();
filePath = context.getFilesDir().getAbsolutePath();
File file = new File(filePath);