i want to make one folder on root and put txt file and append data
'
My java code
public void generateNoteOnSD(String sFileName, String sBody){
try
{
String fileName = "error";
String headings = "Hello, world!";
String path = "/data/root/";
File file = new File(path, fileName+".txt");
if (!file.exists()) {
file.mkdirs();
}
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
// Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
Log.d("file error", ""+e.getMessage());
}
}
I am getting file not found exception
Please help me how can create a file on root folder in internal storage
Try this function.
public void wrtieFileOnInternalStorage(Context mcoContext,String sFileName, String sBody){
File file = new File(mcoContext.getFilesDir(),"mydir");
if(!file.exists()){
file.mkdir();
}
try{
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
}catch (Exception e){
}
}
Try something like this -
public Boolean writeToSD(String text){
Boolean write_successful = false;
File root=null;
try {
// <span id="IL_AD8" class="IL_AD">check for</span> SDcard
root = Environment.getExternalStorageDirectory();
Log.i(TAG,"path.." +root.getAbsolutePath());
//check sdcard permission
if (root.canWrite()){
File fileDir = new File(root.getAbsolutePath());
fileDir.mkdirs();
File file= new File(fileDir, "samplefile.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write(text);
out.close();
write_successful = true;
}
} catch (IOException e) {
Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());
write_successful = false;
}
return write_successful;
}
From here - http://www.coderzheaven.com/2012/09/06/read-write-files-sdcard-application-sandbox-android-complete-example/
In this statement:
File gpxfile = new File(file, sFileName);
file should be directory (you use .txt file here).
Also, read this. You can store you file in /data/data/<your.package.name>/ dir (trying to use /data/root/ will cause Permission denied error).
Try this. Using this, I have created log file in SD card.
public void writeFile(String text){
File tarjeta = Environment.getExternalStorageDirectory();
File logFile = new File(tarjeta.getAbsolutePath()+"/", "log.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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
I am trying to copy an image from the asset folder to the sdcard but doesn't seem to copy it on first launch. It creates the folder okay but doesn't copy the file over.
prefs = getPreferences(Context.MODE_PRIVATE);
if (prefs.getBoolean("firstLaunch", true)) {
prefs.edit().putBoolean("firstLaunch", false).commit();
File nfile=new File(Environment.getExternalStorageDirectory()+"/My Images");
nfile.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("middle.jpg");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images" + filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
}
middle.jpg is the file i want to copy over. Can any one tell me what i am doing wrong?
PS i have WRITE_EXTERNAL_STORAGE in my manifest.
Thanks
You forgot to add / in the end of /My images while constructing the path
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images/" + filename);
out = new FileOutputStream(outFile);
because the filename would be MyImages+Filename so it wouldn't exists for copying.
I want to save my internal storage file into the folder create by my app . Please some one suggest me how it is possible.
My Code :
File sub = new File("/sdcard/myfiles");
sub.mkdirs();
FileOutputStream fout;
try {
fout = openFileOutput("MyPrefs" ,Context.MODE_PRIVATE);
String data="Welcome to Android Internal Storage";
fout.write(data.getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this to save:
//write file
File log = new File("sdcard/MyDirectory/MyFile.txt");
try
{
if (!log.exists())
{
//System.out.println("We had to make a new file.");
log.createNewFile();
}
FileWriter fileWriter = new FileWriter(log, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("dataaaa"+ "%" + "moreDataaa"+ "%" + "moreMoreDataaa");
bufferedWriter.write("******************** " + "\n");
bufferedWriter.close();
//System.out.println("Done");
} catch (IOException e)
{
//System.out.println("COULD NOT LOG!!");
}
i'm writing to you for a problem that i can't solve.
I have a Vector of Vector.
Vector<Vector<Item>> vectorItem;
I don't know how can i save it into a file, and after, how to load.
I try this:
public void save(String name, Context ctx, Vector<Vector<Item>> vectorItem) {
try {
String sdCard = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdCard + "/dir");
File file = new File(dir.getAbsolutePath(), name);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = ctx.openFileOutput(name, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(vectorItem);
oos.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
public Vector<Vector<Item>> load(String name, Context ctx) {
Vector<Vector<Item>> vectorItem; = null;
String sdCard = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdCard + "/dir");
try {
FileInputStream fis = ctx.openFileInput(name);
ObjectInputStream ois = new ObjectInputStream(fis);
vectorItem = (Vector<Vector<Item>>) ois.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return vectorSezioni;
}
But this is the error:
12-29 16:57:07.140: W/System.err(32681): java.io.IOException: open failed: ENOENT (No such file or directory)
First you must guarantee you have WRITE_EXTERNAL_STORAGE permission 'cause you're writing to the SD card.
Before the call to
File file = new File(dir.getAbsolutePath(), name);
you should call
dir.mkdirs();
to be sure the directory gets created.
Then, after you write the object to the output stream, you must flush it for all the data to get written before its closed
oos.flush();
Deserialization method should take into consideration the directory an the file name:
public Vector<Vector<Item>> load(String name, Context ctx) {
Vector<Vector<Item>> vectorItem; = null;
String sdCard = Environment.getExternalStorageDirectory().toString();
File dir = new File(sdCard + "/dir");
File file = new File(dir.getAbsolutePath(), name);
try {
FileInputStream fis = ctx.openFileInput(file);
ObjectInputStream ois = new ObjectInputStream(fis);
vectorItem = (Vector<Vector<Item>>) ois.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return vectorSezioni;
}
Hope it helps.
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();
}
}
}
}