In following code i want to crate a file in sdcard. but it not giving any valid output. showing only the hello world...Where the "file created" message will be displayed and where the file will be stored?
package com.read;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class read extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String FILENAME = "hello_file";
String string = "hello world!";
try{
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}catch(Exception e){}
System.out.println("File created");
}
}
try below code might help you
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File gpxfile = new File(root, "gpxfile.gpx");
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("Hello world");
out.close();
}
}catch (IOException e) {
Log.e(TAG, "Could not write file " + e.getMessage());
}
Note: For this to be working your emulator or device must have SDcard
Edit: For reading the file fromSDCard
try{
File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt");
fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Using this method you're trying to create a file in phone's internal memory.
Just use this code:
FileOuputStream fos = new FileOutputStream( "/sdcard/" + FILENAME );
It will create a file in a root folder of your SD card.
Related
How to append data one by one in existing file? Am using following code.. Append the data row order in file..How to solve this?
private String SaveText() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath()+File.separator+"GPS");
dir.mkdirs();
String fname = "gps.txt";
File file = new File (dir, fname);
FileOutputStream fos;
try {
fos = new FileOutputStream(file,true);
OutputStreamWriter out=new OutputStreamWriter(fos);
out.write(value1);
out.close();
fos.close();
Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
return dir.getAbsolutePath();
}
Try this code
try{
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file,true), "UTF-8");
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write(value1);
fbw.newLine();
fbw.close();
Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
Copy and paste this code.
public void SaveText(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}}
In JAVA 7 you can try:
try {
Files.write(Paths.get(dir+File.separator+fname), latLng.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
checkout Beautiful explanation :here
This is what doing to read from a .txt file in my android activity. Though the app runs, I find that no file is created/appended. In logcat following line is shown,
java.io.FileNotFoundException: /home/Desktop/RiaC_android/Test/app/src/main/assets/SampleFile.txt: open failed: ENOENT (No such file or directory)
The code I'm currently using, though I have tried before,
BufferedWriter out = new BufferedWriter(
new FileWriter("test_File.txt"));
however, the result remains same.
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.widget.TextView;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textView);
File testFile = new File("/home/Desktop/RiaC_android/Test/app/src/main/assets", "SampleFile.txt");
FileWriter writer = null;
try {
writer = new FileWriter(testFile, true);
writer.write("Hello File!!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
if (testFile.exists())
tv.setText("File created!!");
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Any suggestions about what I'm doing wrong?
You can't write file to assets folder.The assets folder is read-only at runtime. Pick a different location to save your data. ie , Environment.getExternalStorageDirectory() don't use Environment.getExternalStorageDirectory().getAbsolutePath().
For reading files from asset use the following method
public String readFromAsset(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
You can't write to /asset directory because it is read-only.
The assets folder is like folders res, src, gen, etc. These are all useful to provide different files as input to build system to generate APK file for your app.
All these are read-only while your app is running. At run-time you can write to SD card.
You do not access assets/ at runtime using File. You access assets/ at runtime using AssetManager, which you can get via getResources().getAssets().
To read from /asset folder, use the following code:
AssetManager assetManager = getResources().getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("SampleFile.txt");
if ( inputStream != null)
Log.d("TAG", "It worked!");
} catch (Exception e) {
e.printStackTrace();
}
You cannot modify files in asset folder. just think them readonly files.
If you want to create text file and modify them, create a file using getExternalCacheDir and new File method.
public static File CreateTextFile(Context context, String filename) throws IOException {
final File root = context.getExternalCacheDir();
return new File(root, filename);
}
EDIT APPENDED BELOW
1. To write text simply, do as below
String text = "bla bla";
FileWriter writer=null;
try {
File file = CreateTextFile("something.txt"); // proposed method
if(!file.exists())
file.createNewFile();
writer = new FileWriter(file);
/** Saving the contents to the file*/
writer.write(text);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2. To read cache file,
Check this link: https://stackoverflow.com/a/5971667/361100
3. One more example
Below example is to write fetched text from internet.
String webUrl = "http://www.yourdata.com/data.txt";
try {
URL url = new URL(webUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
File file = CreateTextFile("something.txt"); // proposed method
if(!file.exists())
file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize)
filepath=file.getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
filepath=null;
}
Could someone look at this snippet of code please and let me know what I'm doing wrong? It's a simple function that takes a string as parameter which it uses as a file name, adding ".txt" to the end of it.
The function checks if the file exists, creating it if it doesn't and then writes two lines of text to the file. Everything appears to be working and the file is created successfully on the sd card. However, after everything is done, the file is empty (and has a size of 0 bytes).
I suspect it's something obvious that I'm overlooking.
public void writeFile(String fileName) {
String myPath = new File(Environment.getExternalStorageDirectory(), "SubFolderName");
myPath.mkdirs();
File file = new File(myPath, fileName+".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
Toast.makeText(this, "Error Creating File", Toast.LENGTH_LONG).show();
return;
}
}
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
// Do whatever
}
}
Hi I will show you the full code I use, works perfect.
I don't use
new OutputStreamWriter()
i use
new BufferedWriter()
here is my Snippet
public void writeToFile(Context context, String fileName, String data) {
Writer mwriter;
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + "myFolder");
if (!dir.isDirectory()) {
dir.mkdir();
}
try {
if (!dir.isDirectory()) {
throw new IOException(
"Unable to create directory myFolder. SD card mounted?");
}
File outputFile = new File(dir, fileName);
mwriter = new BufferedWriter(new FileWriter(outputFile));
mwriter.write(data); // DATA WRITE TO FILE
Toast.makeText(context.getApplicationContext(),
"successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
mwriter.close();
} catch (IOException e) {
Log.w("write log", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external storage.",Toast.LENGTH_LONG).show();
}
}
-- Original Code --
That one took a while to find out. The javadocs
here brought me on the right track.
It says:
Parameters
name The name of the file to open; can not contain path separators.
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_APPEND to append to an existing file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
The file is created, if it does not exist, but it is created in the private app space. You create the file somewhere on the sd card using File.createNewFile() but when you do context.openFileOutput() it creates always a private file in the private App space.
EDIT: Here's my code. I've expanded your method by writing and reading the lines and print what I got to logcat.
<pre>
public void writeFile(String fileName) {
try {
OutputStreamWriter writer = new OutputStreamWriter(
getContext().openFileOutput(fileName + ".txt", Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
// Now read the file
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(
getContext().openFileInput(fileName + ".txt")));
for(String line = is.readLine(); line != null; line = is.readLine())
Log.d("STACKOVERFLOW", line);
is.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
}
Change the mode from Context.MODE_PRIVATE to Context.MODE_APPEND in openFileOutput()
MODE_APPEND
MODE_PRIVATE
Instead of
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
Use
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_APPEND));
UPDATE :
1.
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
OutputStreamWriter writer = new OutputStreamWriter(osr);
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write("First line");
fbw.newLine();
fbw.write("Second line");
fbw.newLine();
fbw.close();
Or 2.
private void writeFileToInternalStorage() {
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
String eol = System.getProperty("line.separator");
BufferedWriter fbw = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(osr);
fbw = new BufferedWriter(writer);
fbw.write("First line" + eol);
fbw.write("Second line" + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fbw != null) {
try {
fbw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
i created a file and when i run the program, the data is been written in to the file but when i run the program again the new data over write on old data.
i need once the program is running and gathers data, these data are writable into the file in cascade next each other without overwriting on previous data in file.
this code running successful but when i run the program again the over writing happens which i don need that, i need to save previous data in side the file and write the new data next it and soon.
after edit this code its looks like:
public class MainActivity extends Activity {
File file;
File sdCard;
FileOutputStream fos;
OutputStreamWriter myOutWriter;
String FileName = "Output3.txt";
String eol;
OutputStream fos1;
FileWriter fw ;
BufferedWriter writer;
BufferedWriter bw ;
PrintWriter out;
EditText txtData;
Button btnWriteSDFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sdCard =getExternalFilesDir(null);
file = new File(sdCard,FileName);
txtData = (EditText) findViewById(R.id.editText1);
btnWriteSDFile = (Button) findViewById(R.id.button1);
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
fos = new FileOutputStream(file);
myOutWriter =new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
please,can any one answer me?
Instead of using OutputStreamWriter use Filewriter FileWriter fileWritter = new FileWriter(file,true); when u pass true it appends the contents.try this
FileWriter myOutWriter = new FileWriter(file.getName(),true);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.write(txtData.getText() + eol);// write this text.
writer.close();
fos.close();
Change this line:
fos = new FileOutputStream(file);
To:
fos = new FileOutputStream(file, true);
This opens the file so that data can be appended.
JavaDocs for FileOutputStream
use
FileWriter writer = new FileWriter("yourfilename", true);
second parameter should be passed as true which will append data instead of overwriting
try {
File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
// this changed bye fos = new FileOutputStream(myFile) to
fos = new FileOutputStream(myFile,true);
//FileWriter writer = new FileWriter("yourfilename", true);
myOutWriter = new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append("\n");
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),
"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT)
.show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Enjoye i have tested it is work for me.
I'm writting an Android's app. Two activities, one has TextEdit to type 'hello message', and button to save message in Internal Storage. Second is main activity. Hello mesage should appear after app's start.
Second activity:
String s = ((EditText) findViewById(R.id.message_act_editText_hello)).getText().toString();
FileOutputStream fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_PRIVATE);
fos.write(s.getBytes());
fos.close();
first (main) activity:
static String FILENAME = "message_file.zip";
FileOutputStream fos;
try {
//piece of code to guarantee that file exists
fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_APPEND);
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis = openFileInput(FILENAME);
messageString = new StringBuffer("");
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast t = Toast.makeText(this, messageString, 3000);
t.show();
I'm getting IO Exception in logcat at line:
while ((length = fis.read(buffer)) != -1)
but app seems to work correctly (defined message appears after app's start). I tried to find explanation, I found several topics, but all was according to large files, or files in assets, or compressed files.
I tried to name my file like
static String FILENAME = "message_file.zip",
static String FILENAME = "message_file.txt",
to try different extensions, but always i'm getting the same IO Exception.
Thanks for suggestions.
of course you will get an IO Exception your file doesn't exit and you request to open it
You forget this peice of code
File myFile = new File("/sdcard/mysdfile.txt");
In your first activity you can use this code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
EditText txtData;
Button btnWriteSDFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),SecondActivity.class);
startActivity(i);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
});
}
}
in the second one you can use this:
public class SecondActivity extends Activity {
private TextView txtData2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
txtData2 = (TextView) findViewById(R.id.textView2);
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData2.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
The first latout uses a linearlayout that contain an edittext and a button
The second a linearLayout with only a textview
Try it works fine if you find problem let me know!!
Ah i forget you have to add in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I found reason. Problem was in fragment:
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
What's the catch?
fis.close();
should be after while. I didn't notice that yesterday...