Android file exists problems - android

When i make File file = new File(etc..) i actuly created that file on SD card? Iam bit confused because everytime my condition is true and program jumps in if tree but in that time there is no file on SD card...
String filename = "pictures.data";
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/courier/saved/");
File file = new File(dir,filename);
if (file.exists())
// program jumps here
else{
}

OK so you can see the file in a dir /courier/saved/. Anyway here's my answer
String filename = "pictures.data";
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/courier/saved/");
File file = new File(dir,filename);
file.mkdirs();
if (file.exists())
// program now stops here
else{
}
Best would be to create the dir beforehand maybe, But this creates it on the fly

Related

Creating a directory on external sd card that will have a text file written to it

I am trying to create a folder on my external SDcard that will contain a text file that I can pull off my phone from my PC and read it.
I have pieced together a snippet that I believe should work, but I cannot find the folder that is supposedly being created.
File path = Environment.getExternalStorageDirectory();
File dir = new File(path.getAbsolutePath() + "/iptestdata/");
if (!dir.exists()) {
dir.mkdirs();
}
String fileName = new SimpleDateFormat("yyyyMMddHHmmss'.txt'").format(new Date());
final File file = new File(dir, fileName);
As I am stepping though the debugger in Android Studio, I see the path being created and stored in dir is /storage/emulated/0/iptestdata, and I see the file name appearing in the format that I requested, but I cannot find the file via File Explorer in Windows. How can I fix this?
If you create File and store into storage Directory you want to call mkdirs()
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath() + " /dir - name /");
dir.mkdir();
File file = new File(dir, "File-Name.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
String data = "This is the content of my file";
os.write(data.getBytes());
os.close();
Please check the Directory is created or not the following method
public static boolean canWriteOnExternalStorage() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.v("Activity", "Yes, can write to external storage.");
return true;
}
return false;
}
Add Permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

android read/save internal storage

I need to save file into internal storage, an then read it.
For save it i do something like this:
// Create directory into internal memory;
File mydir = getActivity().getDir("modelli", Context.MODE_PRIVATE);
File a = new File(mydir, obj_id);
a.mkdir();
File b = new File(mydir, obj_id);
if (obj_type != "modello"){
b = new File(a,obj_type);
b.mkdir();
}
String filename = "";
if(obj_imageName != null)
{
filename = obj_imageName + "." + getFileExtension(urlString);
}
else
{
filename = getFileName(urlString);
}
final File file = new File(b, filename);
file.createNewFile();
but I don't know how read it, with this I get an error (contains a path separator):
File mydir = getActivity().getDir("app_modelli/2/images", Context.MODE_PRIVATE);
where is the mistake? is correct my approach for write file?
You better put them in internal files dir. Both for writing and reading you could use a File object like:
String fileName = "info.txt";
File file = new File ( getInternalFilesDir() + "/" + fileName);
At the moment your code only creates a file with length 0. You are not writing/saving anything to it.

Writing File in External SD card in android

I have tried so many ways to write file in external as card but not working. Please suggest me what to do.
The code snippet that I wrote is as follows:
final String directoryFile = "file:///"+"mnt/extsd/Test";
String filename = "TextData.txt";
Context context;
//String file=Environment.getExternalStorageDirectory()+ "/TextData.txt";
//String file = "mnt/extsd/TextData.txt";
//String file=Environment.getExternalStorageDirectory()+ "/RudimentContent/test.txt";
//File root = android.os.Environment.getExternalStorageDirectory();
//File dir = new File (root.getAbsolutePath() + "/download");
//File path = Environment.getExternalStorageDirectory();
//String filename = "TextData.txt";
//String fileName = "TextData.txt";
//String path = "Environment.getExternalStorageDirectory()/TextData.txt";
//File path = Environment.getExternalStorageDirectory();
public void onClick(View v)
{
// write on SD card file data in the text box
// dir.mkdirs();
//File file = new File(dir, "myData.txt");
//String fileName = surveyName + ".csv";
//String headings = "Hello, world!";
//File file = new File(path, fileName);
//path.mkdirs();
//OutputStream os = new FileOutputStream(file);
//os.write(headings.getBytes());
//create path
//create file
//File outFile = new File(Environment.getExternalStorageDirectory(), filename);
//File directoryFile = new File("mnt/extsd", "Test");
//directoryFile.mkdirs();
//create file
//File file = new File(Environment.getExternalStorageDirectory(), filename);
try{
File myFile = new File(directoryFile, filename); //device.txt
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+myFile.getPath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
I have commented on so may tried codes also. When I write in internal sd card then its working but not with external. Please suggest.
I had this before.
The reason you're having this exception is due to some bizarre ways the framework handles files and folders.
on my case was that I was testing, and all was working, and I deleted the testing folder and since then the system keeps trying to write on the deleted folder. I removed the project from the phone and reboot it and started working again.
furthermore, I suggest you a quick reading on this answer What is the best way to create temporary files on Android? and the comments of this answer... as there is a lot of useful information if you want to create a good app.
just set permission like this
android.permission.WRITE_EXTERNAL_STORAGE
If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory).
This method will create the appropriate directory if necessary.
If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory:
/Android/data//files/
You will have to set the permissions too:
android.permission.WRITE_EXTERNAL_STORAGE
try this
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT: By using this line you can able to see stores images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));

Android: how to set the path for saving files etc like in windows we write c:/someting/...what will I do in android

I am trying to record voice and save it in a file. For this I have to give a path to save the file, but I don't know how will I set the path...I have recently started working on android phone. In windows we set path like a drive e.g. C:/folder/folder....in android phone what will be my root? Where can I save an audio file? Write now I am working on emulator...Will the path be same for both emulator and phone?
we can create file like this in SD card
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/folder");
myDir.mkdirs();
String fname = "file";
File file = new File (myDir, fname);
file is the path of file where you stored.
and add this Permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
_path=Environment.getExternalStorageDirectory().getPath() + "/RECORDS/";
// || ||
// VV VV
// storage path folder name
fileName = String.format("filename.mp3");
File file = new File(_path, fileName);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Save your file in Sdcard.
File path = Environment.getExternalStorageDirectory();
String cardName = path.getName();
path=cardName+"/mypathname/file_name.mp3";
It is also possible in emulator. create sdcard , when you create emulator.
Thanks
Uri outputFileUri;
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "myDir" + File.separator);
root.mkdirs();
sdImageMainDirectory = new Filenter code here(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);

How to check if a file exists in a directory in sd card

I want to check whether a given file exists in android sd card. I am trying it out with creating a file using the absolute path and checking with file.exists() but its not working. The URL for the file is "file:///mnt/sdcard/book1/page2.html" and the file does exist. But somehow file.exists() isn't showing the same.
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "/book1/page2.html");
if(myFile.exists()){
...
}
This should work.
Try like this:
File file = new File(Environment.getExternalStorageDirectory() + "/book1/page2.html");
if (file.exists()) {
/*...*/
}
Also make sure you have:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
in your manifest file.
You can check as follows:
File file = new File(getExternalCacheDirectory(), "mytextfile.txt" );
if (file.exists()) {
//Do action
}
File logFile = new File(
android.os.Environment.getExternalStorageDirectory()
+ "/book1/", "page2.tml");
if (logFile.exists())
System.out.println("file exists");
else
System.out.println("file does not exist
Do something like this :
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "your/file/path");
if(yourFile.exists())
{
}
String filepath = getFilesDir().getAbsolutePath();
String FileName = "Yourfilename" ;
File FileMain = new File(filepath, FileName);
if (FileMain.exists()){
do somthing here
}else{}
File file = new File(path+filename);
if (file.exists())
{
//Do something
}
checked, this will work

Categories

Resources