createNewFile - open failed: ENOENT (No such file or directory) - java

I can't figure out what's going wrong here...I've tried writing this more succicinctly, that didn't work. I put in all the extra strings after reading other suggestions with this problem. Not helping. No clue what's happening. Could it be permissions-related? AFAIK I'm trying to write to internal memory and that doesn't need special permissions?
public void outputBitmap(){
String path = Environment.DIRECTORY_PICTURES.toString();
File folder = new File(path + "/Blabla");
String filename = new SimpleDateFormat("yyMMddHHmmss").format(Calendar.getInstance().getTime()) + ".png";
try {
if (!folder.exists()) {
folder.mkdirs();
System.out.println("Making dirs");
}
File myFile = new File(folder.getAbsolutePath(), filename);
myFile.createNewFile();
FileOutputStream out = new FileOutputStream(myFile);
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
It goes "Making dirs" every time, the directory is not staying made, or something. When it gets to myFile.createNewFile(); it gives the error message "open failed: ENOENT (No such file or directory)"
Not sure if it's related, but the information I am trying to output is from:
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
myBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.RGB_565);
Canvas pngCanvas = new Canvas(myBitmap);
...[some maths and stuff]
canvas.drawLine(...);
pngCanvas.drawLine(...);
}
I thought I should be able to use the same canvas for the bitmap, but that caused crashed, so I'm writing the same information to both canvases. So...I don't know if that's related to the issue or a totally different bad issue or what.
Been searching all kinds of questions that seemed similar, but couldn't find any solutions that worked for me. I've been trying to solve this for days now. Anyone know what's going wrong?
Thanks

You are not using Environment.DIRECTORY_PICTURES correctly. It is not a folder by itself, you need to use it as a parameter to getExternalStoragePublicDirectory() method.
Check here : http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)

Possible Issue:
Make sure you have given following required permission in your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And for Marhsmallow devices, make sure Contacts Groups Permissions is granted too by device user.
Ref: http://developer.android.com/training/permissions/requesting.html

Just change the begining of your code from this:
public void outputBitmap(){
String path = Environment.DIRECTORY_PICTURES.toString();
File folder = new File(path + "/Blabla");
To this:
public void outputBitmap(){File folder = new File(getActivity().getExternalFilesDir(null) + IMAGE_DIRECTORY + "whatever you want for your directory name");

Related

Deleting a txt File [duplicate]

This is currently what I have to delete the file but it's not working. I thought it may be permission problems or something but it wasn't. The file that I am testing with is empty and exists, so not sure why it doesn't delete it.
UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
file.delete();
Any help would be GREATLY appreciated!
I now have:
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();
To try and find the correct path at run time so that if the program is transferred to a different computer it will still find the file.
The problem could also be due to any output streams that you have forgotten to close. In my case I was working with the file before the file being deleted. However at one place in the file operations, I had forgotten to close an output stream that I used to write to the file that was attempted to delete later.
Be sure to find out your current working directory, and write your filepath relative to it.
This code:
File here = new File(".");
System.out.println(here.getAbsolutePath());
... will print out that directory.
Also, unrelated to your question, try to use File.separator to remain OS-independent. Backslashes work only on Windows.
I got the same problem! then realized that my directory was not empty. I found the solution in another thread: not able to delete the directory through Java
/**
* Force deletion of directory
* #param path
* #return
*/
static public boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
Try closing all the FileOutputStream/FileInputStream you've opened earlier in other methods ,then try deleting ,worked like a charm.
I suspect that the problem is that the path is incorrect. Try this:
UserInput.prompt("Enter name of file to delete");
String name = UserInput.readString();
File file = new File("\\Files\\" + name + ".txt");
if (file.exists()) {
file.delete();
} else {
System.err.println(
"I cannot find '" + file + "' ('" + file.getAbsolutePath() + "')");
}
If you want to delete file first close all the connections and streams.
after that delete the file.
In my case it was the close() that was not executing due to unhandled exception.
void method() throws Exception {
FileInputStream fis = new FileInputStream(fileName);
parse(fis);
fis.close();
}
Assume exception is being thrown on the parse(), which is not handled in this method and therefore the file is not closed, down the road, the file is being deleted, and that delete statement fails, and do not delete.
So, instead I had the code like this, then it worked...
try {
parse(fis);
}
catch (Exception ex) {
fis.close();
throw ex;
}
so basic Java, which sometimes we overlook.
As other answers indicate, on Windows you cannot delete a file that is open. However one other thing that can stop a file from being deleted on Windows is if it is is mmap'd to a MappedByteBuffer (or DirectByteBuffer) -- if so, the file cannot be deleted until the byte buffer is garbage collected. There is some relatively safe code for forcibly closing (cleaning) a DirectByteBuffer before it is garbage collected here: https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L606 After cleaning the ByteBuffer, you can delete the file. However, make sure you never use the ByteBuffer again after cleaning it, or the JVM will crash.

java.io.FileNotFoundException: (Permission denied) when writing an object using ObjectOutputStream

I have been trying to work around this for several hours and I am extremely frustrated so I am coming to you guys for some guidance.
I am trying to save and retrieve a User object I have created. I want to make it so that I can save and retrieve this User object from any intent throughout my application, so I decided to go with a FileInput and Output stream. I have included my code for both below.
Here is my output data method:
public static void serializeDataOut(User ish) {
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File newFile = new File(path + "myFile.ser");
FileOutputStream fos = new FileOutputStream(newFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(ish);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And here is my input data method:
public static User serializeDataIn(){
try{
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
FileInputStream fin = new FileInputStream(path + "myFile.ser");
ObjectInputStream ois = new ObjectInputStream(fin);
User iUser = (User) ois.readObject();
ois.close();
return iUser;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
Note: both of these methods reside inside my User class, which also implements Serializable.
The whole error with the file path looks like this: java.io.FileNotFoundException: /storage/emulated/0myFile.ser (Permission denied) and it appeared at this line: FileOutputStream fos = new FileOutputStream(newFile); when I called it from a different intent like so: User.serializeDataOut(addingUser); in which addingUser was a valid User object.
The first thing I did after seeing (Permission denied) in the exception log, was go into my manifest and check if I was allowing my application to read and write to storage, which I did in fact do. I have included my permissions below:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Then I read that some people were having this error if they had the wrong path, more specifically not including the absolute path, which I then edited my code to include the Environment.getExternalStorageDirectory().getAbsolutePath(); part, which I am pretty sure I am using correctly.
I also made sure that, since I am testing this on an emulator, that I had enabled an SD card and the emulator had an SD folder. I checked and it indeed did have an SD card folder, and I also tested this application on an S8 and I got the same error.
What exactly am I doing wrong here? All I want to do is save one User object and retrieve it somewhere else, and I am perfectly ok with a previous file being overwritten and only having one User saved at a time.
Also something that is probably related I just noticed: about every 3-5 seconds in my Android Monitor, an error keeps on popping up non stop even after I kill my application. The error looks like this: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream Although I can only assume this isn't the source of the problem, I just wanted to add it in, in case it could help. Thanks
You've added the permission in manifest, So I'm sure you are not asking runtime permissions. If you are using SDK 23 or higher, Ask runtime permission. For reference I'm adding some snippet here:
if(Build.VERSION.SDK_INT>22){
requestPermissions(new String[] {YOUR_PERMISSIONS AS STRING}, 1);
}
and to check whether permission is granted or not, you need to use onRequestPermissionResults() method.
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (!(grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
Toast.makeText(addAlarm.this, "Permission denied to access your location.", Toast.LENGTH_SHORT).show();
}
}
}
}
This java.io.FileNotFoundException: /storage/emulated/0myFile.ser looks like you are missing a '/' in the path.
Use
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + '/';
Beginning in Android 6.0 (API level 23), users grant permissions to
apps while the app is running
Everything you need to know is in :
https://developer.android.com/training/permissions/requesting.html
The other error has nothing to do with it

Opening Android resource file by URI raises FileNotFoundException

I am trying to get a URI to a resource in my res/raw/ directory. The goal is to give this URI to a VideoView, but this has been problematic, and I seem to be unable to open the file with test code.
I have the following test code:
String uri = "android.resource://com.my.package/" + R.raw.sample_video;
File inputFile = new File(uri);
try {
InputStream is = new FileInputStream(inputFile);
byte[] bytes = new byte[50];
is.read(bytes);
Log.d("test", new String(bytes));
} catch(IOException e) {
}
The new FileInputStream line throws a FileNotFoundException regardless of what variation i try on the URI, but every piece of evidence I see seems to agree that this is the correct form.
For reasons relating to the architecture of the project, the Resource methods that return an InputStream directly aren't an option here, so the URI is the only option that I can see.
What is going wrong? Am I mistaken in how to specify the URI for this file? Is this test code not representative of whether or not the VideoView will be able to read the file? If not, what is? Does this test code work for you (which would indicate that something must be wrong with my project configuration)?
To get the URI of sample_video in raw folder :
Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/"
+ R.raw.sample_video); //do not add any extension
To play the video :
videocontainer.setVideoURI(Uri.parse(videoUri));
videocontainer.start();
where videocontainer of type videoview.

how to copy database from SD Card to //database

I'm sorry for a rather green question, but I could not find solution yet.
I am trying to restore a database from a back up on SD Card. The following code (a slight modified version of one provided here in SO)
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath =
"\\data\\com.dg\\databases\\" + com.dg.Constants.db_Table;
String backupDBPath = "com.dg";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel dst = new FileInputStream(currentDB).getChannel();
FileChannel src = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
line4.setText("Successful Import");
}
} catch (Exception e) {
line4.setText(e.toString());
}
Throws NonWriteableChannelException even though the database file is not open.
Your data is GENERALLY in
/data/data/com.dg/databases
You need to get rid of the double \ in the path.
Also, you're using Environment.getDataDirectory() as the parent directory, then "\data\com.dg\databases\"(etc) as the file name. That's totally wrong.
The easy way to go might be 'getDatabasePath' in Context (or Activity). Give it the name of your DB and it should give you a File reference to it. However, I don't know what it would do if that File didn't exist yet.
http://developer.android.com/reference/android/content/Context.html#getDatabasePath(java.lang.String)
You may also try simple 'getDir("databases", MODE_PRIVATE)'. That would hopefully return the database dir.
Final try for the database dir, really dirty:
File dbDir = new File(getFilesDir().getParentFile(), "databases");
Does your user / app have permissions to //database? (If not, then THIS IS THE ANSWER.)
Perhaps this might tell you why permission is denied:
IOException: Permission Denied
Bill Mote (from the above link) also pointed out the following permission setting:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Caused by: java.io.FileNotFoundException: /path/somthing.jar (Is a directory) when FileOutputStream object is created

this is a really basic one, but it got me scratch my hear for 4 hours, now i'm giving up.
to give as much as possible information , i can say it's a java webapp project with zk 5.0.8 as frontend+spring+hibernate+maven under ubuntu 11.04 with permission to the basedir set to 777.
tried the file upload everything seems to be ok and where i have confidence that my code is correct it's just not working.
here is the code
private boolean saveUploadledFile(Media uploadedMedia, String basedir) {
String code = codeGenerator.generateContentCode(15);
String FINAL_DIR_PATH = basedir + "/"+"Racing" + "/" + code;
String FINAL_FILE_PATH = FINAL_DIR_PATH + "/" + uploadedMedia.getName();
alert(FINAL_DIR_PATH);
try {
File finaldir = new File(FINAL_DIR_PATH);
//apache commons
FileUtils.forceMkdir(finaldir);
alert("Size equals" + uploadedMedia.getByteData().length);
fout = new FileOutputStream(new File(FINAL_DIR_PATH+"/"+addContentWindow1$txtName.getText()+".jar"));
//apache commons
IOUtils.copy(uploadedMedia.getStreamData(), fout);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(fout);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return false;
}
new FileOutputStream always throws exceptions. so if i can't specify where i want to save how to save the files. any ideas? i intentionally output the size of the file to make sure there is a file. Can anyone shed some light? thanks for reading this
the actual exception is
Caused by: java.io.FileNotFoundException: /joseph/mbcs/Games/Racing/20314/somthing.jar (is a directory)
I may be wrong, but isn't this part of your code faulty?
if (!finaldir.exists()) {
if (!finaldir.canWrite())
finaldir.mkdirs(); // this creates no directory no error
else
alert("Cannot write to the directory" );
}
If the directory doesn't exist, you check if you can't write there and then create it, otherwise you output an error. I think that ! there is wrong.
Might be the reason for your problem but it just as well might not be.
Leave out:
if(finalfile.canWrite()) {
as you just created the file and are writing to it.
You will get a misnamed FileNotFoundException (I think renamed in Java 7) when the OutputStream constructor failed in writing.
Another tip, general work like copying may be done using apache-commons (IOUtils, FileUtils),
i.e.:
import org.apache.commons.fileupload.util.Streams;
Streams.copy(in, out, false);

Categories