try {
PrintStream out = new PrintStream(openFileOutput("OutputFile.txt", MODE_PRIVATE));
str=mIn.getText().toString();
out.println(str);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
i want to ask if this code create file called(OutputFile)?and if yes where is the path of this file??
i want to ask if this code create file called(OutputFile)
it creates a file called OutputFile.txt
and if yes where is the path of this file??
you can retrieve its path using getFileStreamPath, which returns the file created with openFileOutput
File file = getFileStreamPath("OutputFile.txt");
String path = null;
if (file != null) {
path = file.getPath();
}
Related
I searched and tried a lot before asking this.
But all the code that I'm trying is not working.
I want the file to be stored in the download folder and be accessible from the user also if he uninstalls the app.
I also tried using opencsv library. Could you provide a tested way to create a csv or txt file and store to download folder?
Save to to publicDir(Downloads folder) you first need permission.WRITE_EXTERNAL_STORAGE
check docs
Note this won't work without permmissions
private void saveData(){
String csv_data = "";/// your csv data as string;
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
//if you want to create a sub-dir
root = new File(root, "SubDir");
root.mkdir();
// select the name for your file
root = new File(root , "my_csv.csv");
try {
FileOutputStream fout = new FileOutputStream(root);
fout.write(csv_data.getBytes());
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
boolean bool = false;
try {
// try to create the file
bool = root.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
if (bool){
// call the method again
saveData()
}else {
throw new IllegalStateException("Failed to create image file");
}
} catch (IOException e) {
e.printStackTrace();
}
}
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 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
This is how I create the file:
File directory = null;
File file = null;
try {
directory = new File(this.getExternalFilesDir(null));
} catch (Exception ex) {
ex.printStackTrace();
if (!directory.exists()) {
directory.mkdirs();
}
}
file = new File(directory, "user_data.json");
if (!file.exists()) {
try {
file.getParentFile().mkdirs();
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
and then this file appears in:
Android/data/com.mypackage.asd/files/user_data.json
but later on when I need it, using this code:
FileInputStream fis = null;
try {
fis = context.openFileInput("user_data.json");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I get a NullPointerException and I see that the system looks for the file in
data/data/com.mypackage.asd/files/user_data.json
Why does it replace "Android" with "data" in the path?
In the first case, you are using getExternalFilesDir().
In the second case, you are using openFileInput().
Those are not pointing to the same place.
If you want your file to be placed onto external storage, use getExternalFilesDir() everywhere.
If you want your file to be placed onto internal storage, use getFilesDir() and/or openFileInput().