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!
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
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>
I am creating an android application which reads and writes data to a file in the location /sdcard/ReadandWrite/.when i writing to that file it does not write in append mode.it will removes the old data and writes the new one.please help me to solve this.Here is my code.
private File openfile() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/ReadandWrite");
dir.mkdirs();
File file = new File(dir, "myfile.txt");
file.setWritable(true);
if(file.exists())
{
file.canRead();
file.setWritable(true);
}
else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
private void writetofile() {
try {
File file=openfile();
OutputStreamWriter myOutWriter =
new OutputStreamWriter(new FileOutputStream(file));
myOutWriter.append(text.getText());
myOutWriter.close();
myOutWriter.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
You need to configure the FileOutputStream to use append mode. From JDK documentation:
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Creates a file output stream to write to the file with the specified
name. If the second argument is true, then bytes will be written to
the end of the file rather than the beginning. A new FileDescriptor
object is created to represent this file connection.
First, if there is a security manager, its checkWrite method is called
with name as its argument.
If the file exists but is a directory rather than a regular file, does
not exist but cannot be created, or cannot be opened for any other
reason then a FileNotFoundException is thrown.
Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning Throws:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or
cannot be opened for any other reason.
SecurityException - if a security manager exists and its checkWrite method denies write access to the file. Since:
JDK1.1 See Also:
SecurityManager.checkWrite(java.lang.String)
So change
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file));
to
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file, true));
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 try to create 'foo/bar.txt' in Android's /data/data/pkg/files directory.
It seems to be a contradiction in docs:
To write to a file, call Context.openFileOutput() with the name and path.
http://developer.android.com/guide/topics/data/data-storage.html#files
The name of the file to open; can not contain path separators.
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String,%20int)
And when I call
this.openFileOutput("foo/bar.txt", Context.MODE_PRIVATE);
exception is thrown:
java.lang.IllegalArgumentException: File foo/bar.txt contains a path separator
So how do I create file in subfolder?
It does appear you've come across a documentation issue. Things don't look any better if you dig into the source code for ApplicationContext.java. Inside of openFileOutput():
File f = makeFilename(getFilesDir(), name);
getFilesDir() always returns the directory "files". And makeFilename()?
private File makeFilename(File base, String name) {
if (name.indexOf(File.separatorChar) < 0) {
return new File(base, name);
}
throw new IllegalArgumentException(
"File " + name + " contains a path separator");
}
So by using openFileOutput() you won't be able to control the containing directory; it'll always end up in the "files" directory.
There is, however, nothing stopping you from creating files on your own in your package directory, using File and FileUtils. It just means you'll miss out on the conveniences that using openFileOutput() gives you (such as automatically setting permissions).
You can add files with path in private directory like that
String path = this.getApplicationContext().getFilesDir() + "/testDir/";
File file = new File(path);
file.mkdirs();
path += "testlab.txt";
OutputStream myOutput;
try {
myOutput = new BufferedOutputStream(new FileOutputStream(path,true));
write(myOutput, new String("TEST").getBytes());
myOutput.flush();
myOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Use getFilesDir() to get a File at the root of your package's files/ directory.
To write to a file in a subfolder of internal storage you will need to create the file (and subfolder if not already there) first, then create the FileOutputStream object.
Here is the method I used
private void WriteToFileInSubfolder(Context context){
String data = "12345";
String subfolder = "sub";
String filename = "file.txt";
//Test if subfolder exists and if not create
File folder = new File(context.getFilesDir() + File.separator + subfolder);
if(!folder.exists()){
folder.mkdir();
}
File file = new File(context.getFilesDir() + File.separator
+ subfolder + File.separator + filename);
FileOutputStream outstream;
try{
if(!file.exists()){
file.createNewFile();
}
//commented line throws an exception if filename contains a path separator
//outstream = context.openFileOutput(filename, Context.MODE_PRIVATE);
outstream = new FileOutputStream(file);
outstream.write(data.getBytes());
outstream.close();
}catch(IOException e){
e.printStackTrace();
}
}
Assuming the original post sought how to both create a subdirectory in the files area and write a file in it, this might be new in the docs:
public abstract File getDir (String name, int mode)
Since: API Level 1
Retrieve, creating if needed, a new directory in which the application
can place its own custom data files. You can use the returned File
object to create and access files in this directory. Note that files
created through a File object will only be accessible by your own
application; you can only set the mode of the entire directory, not of
individual files.