I want to save a file in internal storage.The next step is i want to read the file.
The file is created in the internal storage using FileOutputStream but there is problem in reading the file.
Is it possible to access internal storage to read the file?
Yes you can read file from internal storage.
for writing file you can use this
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
to read a file use the below:
To read a file from internal storage:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read(). Then close the stream with close().
Code:
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om) {
om.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
String result = sb.toString();
Refer this link
It is possible to write and read the text file from internal storage. In case of internal storage there is no need to create the file directly. Use FileOutputStream to write to file. FileOutputStream will create the file in internal storage automatically. There is no need to provide any path, you only need to provide the file name. Now to read the file use FileInputStream. It will automatically read the file from internal storage. Below I am providing the code to read and write to file.
Code to write the file
String FILENAME ="textFile.txt";
String strMsgToSave = "VIVEKANAND";
FileOutputStream fos;
try
{
fos = context.openFileOutput( FILENAME, Context.MODE_PRIVATE );
try
{
fos.write( strMsgToSave.getBytes() );
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
CODE TO READ THE FILE
int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis;
try {
fis = context.openFileInput( FILENAME );
try {
while( (ch = fis.read()) != -1)
fileContent.append((char)ch);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String data = new String(fileContent);
This thread seems to be exactly what you are looking for Read/write file to internal private storage
Has some good tips.
Absolutely Yes,
Read this http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Related
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();
}
}
developer data-storage-files
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();
}
private String readfile(){
String content="";
try{
InputStream inputStream=openFileInput(myfile);
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() ;
content=stringBuilder.toString();
}
}
catch (FileNotFoundException e){
Log.e(FILENAME1, "File Not Found"+e.toString());
}catch (IOException e){
Log.e(FILENAME1,"Cannot read file"+e.toString());
}
return content;
}
I try to write a txt file according to this website, say i want to save the data like this way: ever day i save one number after the date
line 1 2014-12-23 3
line 2 2014-12-24 6
line 3 2014-12-25 10
.
.
.
.
But for every time I write data into this file, it seems that the file is overwritten and every time i read the file, this returns me the most update number. I want to save the date and get the data on one specific line. Any suggestions? Thanks a lot!!
Try changing this
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
to
outputStream = openFileOutput(filename, Context.MODE_APPEND);
Also you might have to check if files exists. If it doesn't exist use your original statement and if it does exist then use the statement I have mentioned.
Where is the android data folder exists ?since i have to save large files and users should not able to see them ,i think to use data folder.But i don't know where is located in android phone.does it is on sdcard or not ?
You should use Internal storage
Internal storage is best when you want to be sure that neither the user nor other apps can access your files.
Sample code:
File file = new File(context.getFilesDir(), filename);
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();
}
public File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
catch (IOException e) {
// Error while creating file
}
return file;
}
For more details, please refer here.
Use the below to get the path of of data directory
File f = Environment.getDataDirectory();
System.out.println(f.getAbsolutePath());
how to read a specific file from sdcard. i have pushed the file in sdcard through DDMS and i am trying to read it though this way but this give me exception. can anybody tell me how to point exactly on that file?
my code is this.
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
FileInputStream iStream = new FileInputStream(path);
You are trying to read a directory... what you need is the file! Do something like this... then, you can read the file as you want.
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
To read any file(CSV in my case) from External Storage, we need a path for it,once you have path you can do like this...
void readFileData(String path) throws FileNotFoundException
{
String[] data;
File file = new File(path);
if (file.exists())
{
BufferedReader br = new BufferedReader(new FileReader(file));
try
{
String csvLine;
while ((csvLine = br.readLine()) != null)
{
data=csvLine.split(",");
try
{
Toast.makeText(getApplicationContext(),data[0]+" "+data[1],Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Log.e("Problem",e.toString());
}
}
}
catch (IOException ex)
{
throw new RuntimeException("Error in reading CSV file: "+ex);
}
}
else
{
Toast.makeText(getApplicationContext(),"file not exists",Toast.LENGTH_SHORT).show();
}
}
/*
csv file data
17IT1,GOOGLE
17IT2,AMAZON
17IT3,FACEBOOK*/
File file = new File("android.resource://com.baltech.PdfReader/assets/raw/"+filename);
if (file.exists()) {
Uri targetUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(PdfReaderActivity.this, "No Application Available to View PDF", Toast.LENGTH_SHORT).show();
}
i want to read .pdf file which is in assets folder. what path i hav to give in filename. plz help. Thanks
I'm not sure if you got an answer to this already, seems pretty old, but this worked for me.
//you need to copy the input stream to a new file, so store it elsewhere
//this stores it to the sdcard in a new folder "MyApp"
String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/solicitation_form.pdf";
AssetManager assetManager = getAssets();
try {
InputStream pdfFileStream = assetManager.open("solicitation_form.pdf");
CreateFileFromInputStream(pdfFileStream, filename);
} catch (IOException e1) {
e1.printStackTrace();
}
File pdfFile = new File(filename);
The CreateFileFromInputStream function is as follows
public void CreateFileFromInputStream(InputStream inStream, String path) throws IOException {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(path));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inStream.close();
out.flush();
out.close();
}
Really hope this helps anyone else who reads this.
File file = new File("file:///android_asset/raw/"+filename);
replace the above line with below and try..
File file = new File("android.resource://com.com.com/raw/"+filename);
and place your PDF file raw folder instead of asset. Also change com.com.com with your package name.
Since assets files are stored inside apk file, there is no absolute path of the assets folder.
You might use a workaround creating a new file used as a buffer.
You should use AssetManager:
AssetManager mngr = getAssets();
InputStream ip = mngr.open(<filename in the assets folder>);
File assetFile = createFileFromInputStream(ip);
private File createFileFromInputStream(InputStream ip);
try{
File f=new File(<filename>);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}catch (IOException e){}
}
}