In my application, I want to create a text file in the cache folder and first what I do is create a folder in the cache directory.
File myDir = new File(getCacheDir(), "MySecretFolder");
myDir.mkdir();
Then I want to create a text file in that created folder using the following code that doesn't seem to make it there. Instead, the code below creates the text file in the "files" folder that is in the same directory as the "cache" folder.
FileOutputStream fOut = null;
try {
fOut = openFileOutput("secret.txt",MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String str = "data";
try {
fOut.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
SO my question is, how do I properly designate the "MySecretFolder" to make the text file in?
I have tried the following:
"/data/data/com.example.myandroid.cuecards/cache/MySecretFolder", but it crashes my entire app if I try that. How should I properly save the text file in the cache/MySecretFolder?
use getCacheDir(). It returns the absolute path to the application-specific cache directory on the filesystem. Then you can create your directory
File myDir = new File(getCacheDir(), "folder");
myDir.mkdir();
Please try this maybe helps you.
Ok, If you want to create the TextFile in Specific Folder then You can try to below code.
try {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/MyFolder/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
File f = new File(rootPath + "mttext.txt");
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileOutputStream out = new FileOutputStream(f);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Just change
fOut = openFileOutput("secret.txt",MODE_PRIVATE);
to
fOut = openFileOutput(myDir+"/secret.txt",MODE_PRIVATE);
This will make secret.txt under MySecretFolder
getPrivateDir will create a folder in your private area (Context.MODE_WORLD_WRITEABLE- use what suits you from Context.MODE_...)
public File getPrivateDir(String name)
{
return context.getDir(name, Context.MODE_WORLD_WRITEABLE);
}
openPrivateFileInput will create a file if it doesn't exist in your private folder in files directory and return a FileInputStream :
/data/data/your.packagename/files
Your application private folder is in
/data/data/your.packagename
public FileInputStream openPrivateFileInput(String name) throws FileNotFoundException
{
return context.openFileInput(name);
}
If you package name is uno.due.com your app private folder is:
/data/data/uno.due.com
All directories underneath are weather created by you or by android for you. When you create a file as above it will go under:
/data/data/uno.due.com/files
Simple and easy code to create folder, file and write/append into the file
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/newfoldername/"; // it will return root directory of internal storage
File root = new File(path);
if (!root.exists()) {
root.mkdirs(); // create folder if not exist
}
File file = new File(rootPath + "log.txt");
if (!file.exists()) {
file.createNewFile(); // create file if not exist
}
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append("hi this will write in to file");
buf.newLine(); // pointer will be nextline
buf.close();
}
catch (Exception e) {
e.printStackTrace();
}
NOTE: It needs the Android External Storage Permission so add below line in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Related
I have created a function to save the audio but don't know how to make it work. Would be nice if anybody would help me out?
private void saveAudio(int sound) {
String root = Environment.getExternalStorageDirectory().toString();
if (checkPermissionwrite()) { // check or ask permission
File myDir = new File(root, "/KangleiPdDrums/Sounds");
if (!myDir.exists()) {
myDir.mkdirs();
}
String fname = "Sound1.mp3";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile(); // if file already exists will do nothing
FileOutputStream out = new FileOutputStream(file);
out.write(sound);
out.flush();
out.close();
file.setReadable(true, false);
String pathed = file.getPath();
Toast.makeText(getApplicationContext(), "Saved at " + pathed, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Let me try to explain this
String root = Environment.getExternalStorageDirectory().toString();
In the root variable, he is getting the root reference of the private external storage.
if (checkPermissionwrite()) { }// check or ask permission
Here even this function is not available in your code but this function will use to take the write permission for the user
File myDir = new File(root, "/KangleiPdDrums/Sounds");
if (!myDir.exists()) {
myDir.mkdirs();
}
Here he is creating a directory or folder at the root folder of your external storage and then he is checking if this directory already exists or not if not then create the directory.
String fname = "Sound1.mp3";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
Here he storage the file name in the name folder and create the file and after that, he checked if the file already exists then delete this file.
try {
file.createNewFile(); // if file already exists will do nothing
FileOutputStream out = new FileOutputStream(file);
out.write(sound);
out.flush();
out.close();
file.setReadable(true, false);
String pathed = file.getPath();
Toast.makeText(getApplicationContext(), "Saved at " + pathed, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Here this code is used to write the file/audio at the directory that he created at the start and I think it's simple
Let me provide a link for the Indian and Pakistani users that understand Hindi or Urdu they can understand it through video as well
https://youtu.be/SZPF9KuPIV8
I am trying to write files in the external SD card folder. Even after having set the required permission in the manifest file, I am unable to write on the external SD card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Code:
String path = "/mnt/extsd/nit.txt";
File myFile = new File(path);
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
}
try {
FileOutputStream fostream = new FileOutputStream(myFile);
OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);
bwriter.write("Hi welcome ");
bwriter.newLine();
bwriter.close();
oswriter.close();
fostream.close();
txtText.setText("success");
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
On the other hand when I use ES File Explorer and try to create a file, it creates it without any issues.
Don't use the absolute path String path = "/mnt/extsd/nit.txt"; because you never know about android device being used by users. Rather you can get the external storage directory path by using Environment.getExternalStorageDirectory().toString().
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
File log = new File(Environment.getExternalStorageDirectory(), "your_file_name.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write("any data");
} catch (Exception e) {
}
And don't forget to close the streams.
First check sd-card is available or not.
String state = Environment.getExternalStorageState();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File folder = folder = new File(extStorageDirectory, "FolderName");
if(!folder.exists())
{
folder.mkdir();//making folder
}
File file = new File(folder,"Filename");//making file
}
Please try this code, it work in my application.
I'm writing an Android application in which I want to create text files in a particular folder and afterwards I want to read the files from my device.
I'm doing this way:
File sd = Environment.getExternalStorageDirectory();
File f;
FileWriter fw = null;
String path = sd.getAbsolutePath() + "/Samples/";
f = new File(path+File.separator+"filename.txt");
if (!f.exists())
{
f.mkdirs();//Creates the directory named by this file, creating missing parent directories if necessary
try
{
f.createNewFile();
//fw = new FileWriter(f, true);
}
catch (IOException e)
{
Log.e("ERROR","Exception while creating file:"+e.toString());
}
The problem is that in this way I create another folder instead of a text file. What can I do? Thanks
Instead of:
f.mkdirs();
do:
path.mkdirs();
I found the solution and I want to share it with you:
File sd = Environment.getExternalStorageDirectory();
File folder;
String path = sd.getAbsolutePath() ;
folder = new File(path, dirName);
if (!folder.exists()){
folder.mkdirs();}
try{
File file = new File(folder, fileName+".txt");
file.createNewFile();
} catch (IOException e) {
Log.e("ERROR", "Exception while creating file:" + e.toString());
}
I hope this could help other people having the same problem. Good luck
I am working on a method that writes an XML file to the device. I've allowed external storage in the manifest file, but I can't find the file at the location it should be.
Here is my code:
public static void write (){
Serializer serial = new Persister();
File sdcardFile = new File("/Prueba/file.xml");
Item respuestas = new Item();
try {
serial.write(respuestas, sdcardFile);
} catch (Exception e) {
// There is the possibility of error for a number of reasons. Handle this appropriately in your code
e.printStackTrace();
}
Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());
}
}
Sdcard File path problem. Here is an exaple that write string in file.xml file.
File myFile = new File("/sdcard/file.xml");
try {
File myFile = new File("/sdcard/file.xml");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("encodedString");
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
You able to get External Storage name by this way,
String root = Environment.getExternalStorageDirectory().toString();
I think I have looked at all of the relevant questions and I still can't get this to work.
Here is the code:
File sdCard = Environment.getExternalStorageDirectory();
File directory= new File (sdCard.getAbsolutePath() + appName);
directory.mkdirs();
File file = new File(directory,fileName);
The folder is created, but I get an error saying the file does not exist. appName is a string containing the name of the folder and that works correctly. fileName is a string containing the name of the file I want to include.
I have included the permission in the manifest.
What am I doing wrong?
Update:
The code tries to make a subdirectory and a file at the same time, which hidden because the code uses a named String rather than a String literal. Adding an intermediate step to create the subdirectory solved the problem.
If the directory is created, then you're on the right track. In your code you are not actually creating the file on the SD card. If you need to create the file, then do this:
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + appName + "/" + fileName);
directory.mkdirs();
file.createNewFile()
This is notional only. It would be much better to actually separate your fileName into a separate subfolder and the actual file and handle them separately.
Try this out:
In this I am creating a text file (.txt file) of a string.
public void createFileFromString(String text)
{
File logFile = new File("sdcard/xmlresponseiphone.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();
}
}
Test this, and see what are you missing :)
Try with something like this. In this case I'm saving an image!
For creating the directory:
File directory = new File(Environment.getExternalStorageDirectory()
+ File.separator + appName);
directory.mkdirs();
And for saving into it
public void save(Bitmap graph, Context context, String name, String time, boolean now) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
graph.compress(Bitmap.CompressFormat.PNG, 100, bytes);
// you can create a new file name "test.jpg" in sdcard folder.
String fileName = "";
if (now){
fileName = getDateTime()+"_00"+".png";
}
else {
fileName = time.replace(".txt", ".png");
}
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "appName/" + fileName);
f.createNewFile(); // write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
}
I think the trick is in File.separator!