Create file in specified directory - java

Try to create file in specific directory but it shows the error FileNotFound. Why?
Am I using impossible path? I really don't know, but is seems like the code should be working.
String day=/1;
String zn="/zn";
File_name=zn
String root= Environment.getExternalStorageDirectory().toString();
File_path=root+day;
File file1 = new File(File_path,File_name);
file1.mkdirs();
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream fos= new FileOutputStream(file1);
String l,d,p;
l = lessnum.getText().toString();
d = desc.getText().toString();
p = place.getText().toString();
fos.write(l.getBytes());
fos.write(d.getBytes());
fos.write(p.getBytes());
fos.close();

Change your code as for creating a file on sdcard
String root= Environment.getExternalStorageDirectory().getAbsolutePath();
String File_name = "File_name.Any_file_Extension(like txt,png etc)";
File file1 = new File(root+ File.separator + File_name);
if(!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
In current you you are also missing file Extension with file name so change String zn as zn="/zn.txt";
and make sure you have added Sd card permission in AndroidManifest.xml :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

First you make a directory
String root= Environment.getExternalStorageDirectory().toString();
String dirName =
root+ "abc/123/xy";
File newFile = new File(dirName);
newFile.mkdirs();
then you create a file inside that directory
String testFile = "test.txt";
File file1 = new File(dirName,testFile);
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
then do your file writing operations
try { OutputStream fos= new FileOutputStream(file1);
String l,d,p;
l = lessnum.getText().toString();
d = desc.getText().toString();
p = place.getText().toString();
os.write(l.getBytes());
fos.write(d.getBytes());
fos.write(p.getBytes());
fos.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think this will help you...
Thanks...

you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And check http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29

String root= Environment.getExternalStorageDirectory().toString();
String dirName =
root+ "abc/123/xy";
File newFile = new File(dirName);
newFile.mkdirs();
String testFile = "test.txt";
File file1 = new File(dirName,testFile);
if(!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And and <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
on manifest file...
Thanks...

Here is your latest attempt:
File_path = root + File.separator + day;
File f_dir = new File(File_path);
f_dir.mkdirs();
File file1 = new File(f_dir, File_name);
if (!file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream fos= new FileOutputStream(file1);
If you showed us the complete stacktrace and error message it would be easier to figure out what is going wrong, but I can think of a couple of possibilities:
You are not checking the value returned by f_dir.mkdirs(), and it could well be returning false to indicate that the directory path was not created. This could mean that:
The directory already existed.
Something existed but it wasn't a directory.
Some part of the directory path could not be created ... for one of a number of possible reasons.
The file1.exists() call will return true if anything exists with that pathname given by the object. The fact that something exists doesn't necessarily mean that you can open it for writing:
It could be a directory.
It could be a file that the application doesn't have write permissions for.
It could be a file on a read-only file system.
And a few other things.
If I was writing this, I'd write it something like this:
File dir = new File(new File(root), day);
if (!dir.exists()) {
if (!dir.mkdirs()) {
System.err.println("Cannot create directories");
return;
}
}
File file1 = new File(dir, fileName);
try (OutputStream fos= new FileOutputStream(file1)) {
...
} catch (FileNotFoundException ex) {
System.err.println("Cannot open file: " + ex.getMessage());
}
I only attempt to create the directory if required ... and check that the creation succeeded.
Then I simply attempt to open the file to write to it. If the file doesn't exist it will be created. If it cannot be created, then the FileNotFoundException message should explain why.
Notice that I've also corrected the style errors you made in your choice of variable names.

Related

Text document is becoming file folder

Here is my class, what I am doing wrong. Why is my text document becoming a file folder. Please explain what is going on and how I can correct it. Thank you
public class InputOutput {
public static void main(String[] args) {
File file = new File("C:/Users/CrypticDev/Desktop/File/Text.txt");
Scanner input = null;
if (file.exists()) {
try {
PrintWriter pw = new PrintWriter(file);
pw.println("Some data that we have stored");
pw.println("Another data that we stored");
pw.close();
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
}
} else {
file.mkdirs();
}
try {
input = new Scanner(file);
while(input.hasNext()) {
System.out.println(input.nextLine());
}
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
} finally {
if (input != null) {
input.close();
}
}
System.out.println(file.exists());
System.out.println(file.length());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isFile());
System.out.println(file.isDirectory());
}
}
Thanks. The above is my Java class.
You mistakingly assume Text.txt is not a directory name.
mkdirs() creates a directory (and all directories needed to create it). In your case 'Text.txt'
See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdirs().
It is perfectly fine for a directory to have a . in it.
You could use getParentFile() to get the directory you want to create and use mkdirs() on that.
For additional informations. Here is the différence between the two representaions of files and directories:
final File file1 = new File("H:/Test/Text.txt"); // Creates NO File/Directory
file1.mkdirs(); // Creates directory named "Text.txt" and its parent directory "H:/Test" if it doesn't exist (may fail regarding to permissions on folders).
final File file = new File("H:/Test2/Text.txt"); // Creates NO File/Directory
try {
file.createNewFile(); // Creates file named "Text.txt" (if doesn't exist) in the folder "H:/Test2". If parents don't exist, no file is created.
} catch (IOException e) {
e.printStackTrace();
}
Replace your code:
else {
file.mkdirs();
}
with:
else {
if (!file.isFile()&&file.getParentFile().mkdirs()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}

FileOutputStream : FileNotFoundException when attempting to instantiate

Trying to create and write to a file, but i get a FileNotFoundException every time, here is the method i am using:
public void saveFileAsPRN(Context context){
byte[] dataFile = getPrintableFileData();
String filename = "TestPrn.prn";
// instantiate a file object using the path
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
Log.e(TAG, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
//determine if the media is mounted with read & write access
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(TAG, "media mounted"); //good
}else{
Log.e(TAG, "media NOT mounted"); //bad
}
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
// determine if the file exists, create it if it does not
if(!file.exists()){
try {
Log.e(TAG, "File does not exist, creating..");
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.e(TAG, "File Exists");
}
//this makes the blank file visible in the file browser
MediaScannerConnection.scanFile(context, new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + filename}, null, null);
//create output stream - send data; saving to file
OutputStream out = null;
try {
FileOutputStream fos = null;
fos = new FileOutputStream(file); // <---- CRASHES HERE; FileNotFoundException
out = new BufferedOutputStream(fos);
out.write(dataFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A FileNotFoundException is raised on the following line:
fos = new FileOutputStream(file); // <---- CRASHES HERE;
The directory Exists, and a blank file is created in the target directory (visible by browsing target folder on PC).
Calling the method canWrite() on the File object returns true - i have write access.
The manifest contains: android.permission.WRITE_EXTERNAL_STORAGE"
So i'm out of ideas, i see several people have similar issues, but i cant find an answer.
Commenting out the following code fixed the issue:
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
that code does create a blank file, you can see it contained in the folder,
BUT - it's very misleading; you can't do anything with this file, i tried transferring it from my device to my PC and i couldn't, i also cannot open it. and you cannot open a stream to it in code.
Try this may helps you.
Replace this line
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
With
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), filename);

How to check if file name already exists?

I have a voice recording app and I'm trying to implement a feature that checks if the recorded file with a certain name already exists. If a user types in a file name that already exists, an alert dialog should be shown.
All file names are stored in a .txt file on the device.
My current code:
try {
BufferedReader br = new BufferedReader(new FileReader(txtFilePath));
String line = null;
while ((line = br.readLine()) != null) {
if (line.equals(input.getText().toString())) {
nameAlreadyExists();
}
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
newFileName = input.getText();
from = new File(appDirectory, beforeRename);
to = new File(appDirectory, newFileName + ".mp3");
from.renameTo(to);
writeToFile(input);
toast.show();
This code only works halfway as it should. It does successfully check if the file name already exists. If the file name doesn't yet exist, it will work fine. But if the file name already exists, then the user will get the "nameAlreadyExists()" alert dialog but the file will still be added and overwritten. How do I make my code stop at "nameAlreadyExists()"?
I solved the problem with the following code:
File newFile = new File(appDirectory, input.getText().toString() + ".mp3");
if (newFile.exists())
{
nameAlreadyExists();
}
else
{
newFileName = input.getText();
from = new File (appDirectory, beforeRename);
to = new File (appDirectory, newFileName + ".mp3");
from.renameTo(to);
writeToFile(input);
toast.show();
}
The File class provides the exists() method, which returns true if the file exists.
File f = new File(newFileName);
if(f.exists()) { /* show alert */ }
You can easy write return; to get out from the function (if that is the function). Or use
if(f.exists() /* f is a File object */ ) /* That is a bool, returns true if file exists */
statement, to check if file exists and then do correct things.
Below is the code i used to do the task,
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"My_Folder");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("My_Folder", "failed to create directory");
return null;
}
}
I think you are missing some flag to fork your code in case the file does exist:
boolean fileExists = false;
try {
BufferedReader br = new BufferedReader(new FileReader(txtFilePath));
String line = null;
while ((line = br.readLine()) != null) {
if (line.equals(input.getText().toString())) {
fileExists = true;
nameAlreadyExists();
}
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
if(!fileExists)
{
newFileName = input.getText();
from = new File(appDirectory, beforeRename);
to = new File(appDirectory, newFileName + ".mp3");
from.renameTo(to);
writeToFile(input);
toast.show();
}
and feel free to use the exists() function of File as above....

Android File not created on SD card

I'm trying to create a file on the SD on my device. This worked a week ago, but now it isn't, and I don't understand why.
The Logcat prints:
java.io.FileNotFoundException ...pathtofile... (no such file or directory)
So, the file is not being created. I have the correct permissions on the android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
I create the file this way:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
base = Environment.getExternalStorageDirectory().getAbsolutePath();
}
String fname = File.separator +"VID_"+ timeStamp + ".3gp";
mediaFile = new File(base+fname);
Then I check if it exists:
if(mediaFile.exists()){
Log.v("mediaFile","ex");
}else{
Log.v("mediaFile","no ex");
}
And the log says that IT DOESN'T EXIST. I also have tried with file.createNewFile() and it doesn't work.
So, a week ago it was working, now it doesn't work, it could be a problem with the SD card ???? Could it be some type of BUG!!!????
Thanks
EDIT: More Code
The function where the file is created is :
private static File getOutputMediaFile()
Called from:
private static Uri getOutputMediaFileUri(){
return Uri.fromFile(getOutputMediaFile());
}
And setted to mediarecorder output as:
vMediaRecorder.setOutputFile(getOutputMediaFileUri().toString());
So, when I do mediarecorder.prepare():
try {
vMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.v("RELEASE VIDREC1",e.toString());
releaseMediaRecorder();
return false;
} **catch (IOException e) {
Log.v("RELEASE VIDREC2",e.toString());
releaseMediaRecorder();
return false;**
}
The bold catch is the one that runs, and prints:
java.io.FileNotFoundException ...pathtofile... (no such file or directory)
just try this
String fname = "VID_"+ timeStamp + ".3gp";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
mediaFile = new File(android.os.Environment.getExternalStorageDirectory(),fname);
if(!mediaFile.exists())
{
mediaFile.createNewFile();
}
}
if(mediaFile.exists()){
Log.v("mediaFile","ex");
}else{
Log.v("mediaFile","no ex");
}
You merely create the object mediaFile, not the actual file. Use this:
if(!f.exists()){
f.createNewFile();
}
I tried this, for me it works.
final String filename = "file.3gp";
final String path = Environment.getExternalStorageDirectory() + "/" + filename;
File outputfile = new File(path);
if (!outputfile.exists()) {
try {
outputfile.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
}
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outputfile.toString());
try {
recorder.prepare();
recorder.start();
/*recorder.stop();
recorder.reset();
recorder.release();*/
}
catch (IllegalStateException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
Try and see whether or not it works. If not, can you add the full code of getOutputMediaFile()?
My answer here:
First open the path, then add the file:
String dir = Environment.getExternalStorageDirectory(); // getAbsolutePath is not requried
File path = new File(dir);
File root = new File(path, "VID_"+ timeStamp + ".3gp";);
Thanks for your help, I've solved the problem using old code. It is strange because the "file saving" part has no modification. Thanks for all guys, kinda.

Where will be a file created in android if I do it like this

This function creates a file but I can't figure out where is the file created and if someone has a solution to create a file in a particular directory from the external storage is very welcomed :) thanks a lot
private void writeFileToInternalStorage() {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myfile", MODE_WORLD_WRITEABLE)));
writer.write("This is a test1." + eol);
writer.write("This is a test2." + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
for query
Where will be a file created
it will create in Internal Storage as function name said and that will be like
/data/data/yourApp_package_as_in_manifest/ (can see in DDMS)
for query
if someone has a solution to create a file in a particular directory
from the external storage is very welcomed
as per link Write a file in external storage in Android
.........
** Method to check whether external media available and writable. This is adapted from
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */
private void checkExternalMedia(){
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
tv.append("\n\nExternal Media: readable="
+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}
/** Method to write ascii text characters to file on SD card. Note that you must add a
WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
a FileNotFound Exception because you won't have write permission. */
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
// See https://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
and also add a WRITE_EXTERNAL_STORAGE permission to the manifest
It will be created on internal folder: /data/data/com.package.name/ You cannot access that folder using file browser.
If you want to easily access the file you can try to create it on SD card:
/*...*/
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = baseDir + "/"+ "myFile.txt";
FileOutputStream writer = null;
try {
writer = new FileOutputStream(fileName);
writer.write("This is a test1." + eol);
/*...*/

Categories