Writing and reading from txt file android - java

I know that this is a widely discussed question , but I am really confused with those examples provided on android developers manual .
So , I have a "source.txt" in my res/raw folder .For example I want to write 2 lines in it(for ex. Hello\nWorld) and then read them from another activity. Can anyone write the source code for this , please.

You should replace your .txt file to your extornal or internal storage.And You must give permission for write text from androidManifest.xml
for reading file you can do this
public String readFile(String filePath) {
String jString = null;
StringBuilder builder = new StringBuilder();
File yourFile = new File("/sdcard/" + filepath);
if (yourFile.exists()) {
Log.i("file", "file founded");
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(yourFile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String row = "";
try {
while ((row = bufferedReader.readLine()) != null) {
builder.append(row + "\n");
}
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jString = builder.toString();
}
else {
Log.i("FAIL", "FILE NOT FOUND");
}
return jString;
}
for writing file you can use this
public void writetoFile(String filename,String text) {
File file = new File("/sdcard/" + filename);
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileWriter fileWriter;
try {
//you can change second parametre true or false this is about append or clean and write
fileWriter = new FileWriter(file, false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.append(jsonText);
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Whatever is in your APK file is read-only, therefore you are unable to write to file stored in res/raw source folder as it is still in your APK. if you want to work on file shipped with your app, you need to copy if to internal storage or SD card from APK first so that would allow you to alter the content.

Every file in your apk is read only, so you need to create the file in your internal storage or SD Card. If you just want to send small amount to of data to second activity, you can send data along with intent or use sharedPreference.
If you really want to read and write data to/from SD card then you need to use FileInputStream and OutputStreamWriter to read/write data to a file. Check this tutorial here to see how it's done. http://www.java-samples.com/showtutorial.php?tutorialid=1523

Related

Java Commons IO append multiple files

I am using Commons IO to download files from the internet.
This is the method i am using:
public void getFile(String url){
File f = new File("C:/Users/Matthew/Desktop/hello.txt");
PrintWriter pw = new PrintWriter(f);
pw.close();
URL url1;
try {
url1 = new URL(url);
FileUtils.copyURLToFile(url1, f);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}catch (IOException e1){
e1.printStackTrace();
}
}
Is there a way i can download multiple files using this method and have them all save to the hello.txt file? Using the above method, everything gets overwritten and the last file downloaded will be the one added to the hello.txt file.
Basically, is there a way i can store multiple file downloads in one file.
Thanks.
There is no way using FileUtils. However, if you want to use Apache Commons, I'd suggest you do the following:
File f = new File("C:/Users/Matthew/Desktop/hello.txt");
URL url1;
try {
url1 = new URL(url);
IOUtils.copy(url1.openStream(), new FileOutputStream(f, true));
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
which does more or less the same thing, but uses append mode on the FileOutputStream.

Reading a file from a Res folder

I have put a file "template.html" inside RAW folder and I want to read it into a InputStream. But it is returning me null. Can't understand what is wrong in the below code
e.g. fileName passed as parameter is "res/raw/testtemplate.html"
public String getFile(String fileName) {
InputStream input = this.getClass().getClassLoader().getResourceAsStream(fileName);
return getStringFromInputStream(input);
}
Also, there might be a better solution by putting these files in a particular subfolder and putting it inside Asset folder but then I believe I would need to pass context in AssetManager. I don't understand that solution, sorry I am new to android development. Can someone shed some light regarding how this approach can be achieved.
EDIT
I have started implementing this solution with Assets. Below method is supposed to return a string containing the entire text of the file stored as template.html.
getFile("template.html") // I am sending extension this time
Problem getting error getAssets() is undefined.
public String getFile(String fileName) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
String line;
try {
reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
use this
new BufferedInputStream(getResources().openRawResource(filepath));
this will return a buffered input stream
The file name should be without extension :
InputStream ins = getResources().openRawResource(
getResources().getIdentifier("raw/FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName()));
For this purposes uses assets folder:
assets/
This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.
So, you could easy get access at assets with context: context.getAssets()
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(context.getAssets().open("filename.txt")));
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

Java Android working with InputStream and File

Well, first of all, I'm just learning and don't quite understand what I'm doing.
What I want is to create an Excel file in memory and then it would be possible to send it with ActionBarSherlock's ShareActionProvider to mail for example.
But I got exeption :
11-24 18:45:52.112: W/System.err(22073): java.io.FileNotFoundException: /Competition.xls: open failed: EROFS (Read-only file system)
As I searched for the answer on the web - it's the problem of file being created in the system area which is read-only. But I want to create it in memory.. Somehow. Once again, I don't really understand well how it works - the way I see it - I create .xls file somewhere in the memory. So the explanation would be helpful.
So, here's the code :
private void createFileTosend() {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
File toSend=null;
try {
toSend = getFile();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
inputStream = new BufferedInputStream(new FileInputStream(toSend));
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
/* ignore */
}
try {
outputStream.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
public File getFile() throws IOException, WriteException{
File file=new File("Competition.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
//then goes creation of Excel 's xls file which is not important for the question
workbook.write();
workbook.close();
return file;
}
Once again, don't downvote me, please, I'm just learning
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ass per the error log you post, i guess you didn't read it carefully. IT is saying read only file system. You need to put the above permission ATLEAST in your android manifest.
Do this much and see if there is any more error or not
I have a doubt may be wrong
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
you are using Context.MODE_WORLD_READABLE its readable, so how can you access it in write mode later. Is it right?
Check this link
Use the http://developer.android.com/guide/topics/data/data-storage.html to clear your doubt about file creation

FileOutputStream : FileNotFoundException when attempting to instantiate

Trying to create and write to a file, but i get a FileNotFoundException every time, here is the method i am using:
public void saveFileAsPRN(Context context){
byte[] dataFile = getPrintableFileData();
String filename = "TestPrn.prn";
// instantiate a file object using the path
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
Log.e(TAG, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
//determine if the media is mounted with read & write access
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(TAG, "media mounted"); //good
}else{
Log.e(TAG, "media NOT mounted"); //bad
}
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
// determine if the file exists, create it if it does not
if(!file.exists()){
try {
Log.e(TAG, "File does not exist, creating..");
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.e(TAG, "File Exists");
}
//this makes the blank file visible in the file browser
MediaScannerConnection.scanFile(context, new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + filename}, null, null);
//create output stream - send data; saving to file
OutputStream out = null;
try {
FileOutputStream fos = null;
fos = new FileOutputStream(file); // <---- CRASHES HERE; FileNotFoundException
out = new BufferedOutputStream(fos);
out.write(dataFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A FileNotFoundException is raised on the following line:
fos = new FileOutputStream(file); // <---- CRASHES HERE;
The directory Exists, and a blank file is created in the target directory (visible by browsing target folder on PC).
Calling the method canWrite() on the File object returns true - i have write access.
The manifest contains: android.permission.WRITE_EXTERNAL_STORAGE"
So i'm out of ideas, i see several people have similar issues, but i cant find an answer.
Commenting out the following code fixed the issue:
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
that code does create a blank file, you can see it contained in the folder,
BUT - it's very misleading; you can't do anything with this file, i tried transferring it from my device to my PC and i couldn't, i also cannot open it. and you cannot open a stream to it in code.
Try this may helps you.
Replace this line
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
With
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), filename);

Create file in specified directory

Try to create file in specific directory but it shows the error FileNotFound. Why?
Am I using impossible path? I really don't know, but is seems like the code should be working.
String day=/1;
String zn="/zn";
File_name=zn
String root= Environment.getExternalStorageDirectory().toString();
File_path=root+day;
File file1 = new File(File_path,File_name);
file1.mkdirs();
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream fos= new FileOutputStream(file1);
String l,d,p;
l = lessnum.getText().toString();
d = desc.getText().toString();
p = place.getText().toString();
fos.write(l.getBytes());
fos.write(d.getBytes());
fos.write(p.getBytes());
fos.close();
Change your code as for creating a file on sdcard
String root= Environment.getExternalStorageDirectory().getAbsolutePath();
String File_name = "File_name.Any_file_Extension(like txt,png etc)";
File file1 = new File(root+ File.separator + File_name);
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
In current you you are also missing file Extension with file name so change String zn as zn="/zn.txt";
and make sure you have added Sd card permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
First you make a directory
String root= Environment.getExternalStorageDirectory().toString();
String dirName =
root+ "abc/123/xy";
File newFile = new File(dirName);
newFile.mkdirs();
then you create a file inside that directory
String testFile = "test.txt";
File file1 = new File(dirName,testFile);
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
then do your file writing operations
try { OutputStream fos= new FileOutputStream(file1);
String l,d,p;
l = lessnum.getText().toString();
d = desc.getText().toString();
p = place.getText().toString();
os.write(l.getBytes());
fos.write(d.getBytes());
fos.write(p.getBytes());
fos.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think this will help you...
Thanks...
you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And check http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29
String root= Environment.getExternalStorageDirectory().toString();
String dirName =
root+ "abc/123/xy";
File newFile = new File(dirName);
newFile.mkdirs();
String testFile = "test.txt";
File file1 = new File(dirName,testFile);
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And and <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
on manifest file...
Thanks...
Here is your latest attempt:
File_path = root + File.separator + day;
File f_dir = new File(File_path);
f_dir.mkdirs();
File file1 = new File(f_dir, File_name);
if (!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream fos= new FileOutputStream(file1);
If you showed us the complete stacktrace and error message it would be easier to figure out what is going wrong, but I can think of a couple of possibilities:
You are not checking the value returned by f_dir.mkdirs(), and it could well be returning false to indicate that the directory path was not created. This could mean that:
The directory already existed.
Something existed but it wasn't a directory.
Some part of the directory path could not be created ... for one of a number of possible reasons.
The file1.exists() call will return true if anything exists with that pathname given by the object. The fact that something exists doesn't necessarily mean that you can open it for writing:
It could be a directory.
It could be a file that the application doesn't have write permissions for.
It could be a file on a read-only file system.
And a few other things.
If I was writing this, I'd write it something like this:
File dir = new File(new File(root), day);
if (!dir.exists()) {
if (!dir.mkdirs()) {
System.err.println("Cannot create directories");
return;
}
}
File file1 = new File(dir, fileName);
try (OutputStream fos= new FileOutputStream(file1)) {
...
} catch (FileNotFoundException ex) {
System.err.println("Cannot open file: " + ex.getMessage());
}
I only attempt to create the directory if required ... and check that the creation succeeded.
Then I simply attempt to open the file to write to it. If the file doesn't exist it will be created. If it cannot be created, then the FileNotFoundException message should explain why.
Notice that I've also corrected the style errors you made in your choice of variable names.

Categories