Write file to sdcard in android - android

I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?
// create file
public void createfile(String name)
{
try
{
new FileOutputStream(filename, true).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// write to file
public void appendToFile(String dataAppend, String nameOfFile) throws IOException
{
fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
fosAppend.write(dataAppend.getBytes());
fosAppend.write(System.getProperty("line.separator").getBytes());
fosAppend.flush();
fosAppend.close();
}

Here's an example from my code:
try {
String filename = "abc.txt";
File myFile = new File(Environment
.getExternalStorageDirectory(), filename);
if (!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = string.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And don't forget the:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Try like this,
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
File file = new File(newFolder, "MyTest" + ".txt");
file.createNewFile();
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
} catch (Exception e) {
System.out.println("e: " + e);
}

It's pretty easy to create folder and write file on sd card in android
Code snippet
String ext_storage_state = Environment.getExternalStorageState();
File mediaStorage = new File(Environment.getExternalStorageDirectory()
+ "/Folder name");
if (ext_storage_state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
if (!mediaStorage.exists()) {
mediaStorage.mkdirs();
}
//write file writing code..
try {
FileOutputStream fos=new FileOutputStream(file name);
try {
fos.write(filename.toByteArray());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//Toast message sd card not found..
}

Note: 'getExternalStorageDirectory()'
actually gives you a path to /storage/emulated/0 and not the actual sdcard
'String path = Syst.envr("SECONDARY_STORAGE");' gives you a path to the sd card

Related

Directory not exists in Android

I want to write string of data in a file in android . That is why I have the following code :
public String DumpFile(String fileName,String data)
{
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_data");
myDir.mkdirs();
if(myDir.exists())
Toast.makeText(this, "Directory exists" ,Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "directory not exists " ,Toast.LENGTH_LONG).show();
// Random generator = new Random();
String fname = fileName;
// showToastOnUiThread("File Name: "+fname+" and Data: "+data,
// Toast.LENGTH_LONG);
File file = new File(myDir, fname);
Toast.makeText(this, "Link is "+file.getAbsolutePath(),Toast.LENGTH_LONG).show();
// Toast.makeText(this, "Content is "+data,Toast.LENGTH_LONG).show();
OutputStream bos = null;
FileOutputStream out = null;
if (file.exists())
file.delete();
try {
out = new FileOutputStream(file);
bos = new BufferedOutputStream(out);
bos.write(data.getBytes());
bos.flush();
// out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return fname;
}
But when I have run the code , I have got the Toast that directory not exists . Where is the error ? Can you help me ?
Add the permission to your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Writing to a File in Android

I am just a beginner in learning Android.I want to learn how to write a piece of text to a file in Android.
My code to write, on clicking a button looks like this:
write.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FileOutputStream fos;
try {
fos = openFileOutput("filename", Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tv.setText("Values saved");
}
});
When I execute this the FileNotFoundException is thrown in logcat. As far as I know a new file will be created if no file with such name exists.
The logcat message is:
> 05-14 08:37:55.085: W/System.err(281): java.io.FileNotFoundException: /data/data/com.example.myproject11/files/test (No such file or directory)
First we should check, file is exists or not. Better you try:
File fileDir = new File("filepath");
if (!fileDir.exists())
fileDir.mkdirs();
try {
File file = new File(fileDir, "filename");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(data.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tv.setText("Values saved");

Storing a file to internal storage and reading it

What I am trying to do is store a JSON file as a string in internal storage to access it later. The reasoning behind this is to not have to access the server on every request, as this data is constant. Once it is stored once, it doesn't have to be retrieved again unless there is some sort of update. File storage isn't something I've done before, and I was hoping someone could give me a hand. My current code is throwing a null pointer exception at this line:
File file = new File(getFilesDir(), fileName);
My code:
protected String doInBackground(String[] runeId) {
String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune/" + runeId[0] + "?api_key=" + api_key;
JSONParser jsonParser = new JSONParser();
JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
String jsonString = runeInfo.toString();
String fileName = "runeInfo";
File file = new File(getFilesDir(), fileName);
String readJson = null;
if(!runesCached) {
Log.d("Cache", "Caching File");
try {
FileOutputStream os = new FileOutputStream(file);
os.write(jsonString.getBytes());
os.close();
Log.d("Cache", "Cache Complete");
runesCached = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = null;
try {
FileInputStream fis;
File storedRuneInfo = new File(getFilesDir(), fileName);
fis = new FileInputStream(storedRuneInfo);
fis.read(readJson.getBytes());
JSONObject storedJson = new JSONObject(readJson);
try {
name = storedJson.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
}
Try this, instead:
File file = new File(getFilesDir().toString(), fileName);
getFilesDir() returns a File, not a String, which the File class constructor takes as a parameter.
getFilesDir()toString() should return something like /data/data/com.your.app/
EDIT:
This gives the same error. How about:
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(getFilesDir() + "/" + "filename");
out = new BufferedWriter(fstream);
out.write(jsonString.getBytes());
out.close();
} catch (Exception e){}

Writing byte[] array to text file in Android

So many examples for this question. I tried and still doesn't work.
Test.txt file is created. But no data is written into the test.txt file.
What is wrong with my code? I have permission in the Manifest file as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Code:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();
Cause, you are creating file in SDCard but writing in Internal Storage. Try as follows...
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PrintFiles";
File file = new File(file_path+"/test.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] b = {65,66,67,68,69};
fos.write(b);
fos.flush();
fos.close();
From the doc openFileOutput will
Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.
those files are under the.
data > data > your app id > files
but your file is not in internal folder its in external storage..
Change this line
fos = openFileOutput(file.getName(), Context.MODE_PRIVATE);
into
fos=new FileOutputStream(file);
And try..

How to write entire Logcat in to sdcard?

I need to write entire Logcat in to sdcard not the filtered Logcat. So I tried doing this way
String[] cmd ={"/system/bin/logcat " +"-f"+" /sdcard/d.txt"};
Log.d("NTK","cmd string"+cmd);
Runtime run = Runtime.getRuntime();
Process pr;
try {
pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
System.out.println(line);
Log.i(NTL, "lines"+line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have given all permissions in manifest file too.
Not able to write logcat in to sdcard.
You can have this Tutorial for Reading the Logs. And for writing the logs in the file you can simply use FileWriter give path of the file with file name.
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File gpslogfile = new File(root, "log.txt");
FileWriter gpswriter = new FileWriter(gpslogfile, true);
BufferedWriter out = new BufferedWriter(gpswriter);
out.append(DataToWrite);
out.close();
}
} catch (IOException e) {
Log.d("Log: ", "Could not write file " + e.getMessage());
}

Categories

Resources