Cannot write file to Documents folder - java

I'm trying to write to a file in Java, or create a new file if the file doesn't exist. (Using JDK 14). However, when I run the following code I get an IOException at the if statement condition that reads The system could not find the file specified if the file doesn't exist, and Access is denied if the file does.
File file = new File(filePath);
System.out.println(filePath); // C:\Users\username\Documents\test.txt
if (file.createNewFile()) {
System.out.println("File successfully created");
} else {
System.out.println("File already exists");
}
The code works when I attempt to save it to the desktop folder and saves the file successfully, but for whatever reason isn't allowed to touch Documents.
The user I'm running IntelliJ as has full access to all files on the computer, and running the IDE as administrator did not fix the problem. However, I can save to the user folder and the desktop. It is only Documents or child directories of it that I can't save to.
There are a few similar questions on the site such as this one, however the cause is not the same as in my case this is a permissions issue, and not an issue of a missing directory.

I've just hit this same issue. It seems that JFileChooser() on some Windows 10 installations doesn't tell the os that the user has selected a folder and as such Sandboxing, Malware Control, Access control blocks access to create a file even though the user had full access (permission checks are OK but file write fails with IOException 13 or Access Denied). However FileDialog() DOES work where JFileChooser fails...

Heres what I would do to try to debug this:
Should you be trying to save to 'My Documents' as opposed to 'Documents'?
Try to save the file to C:\Users\username\test.txt (I suspect that will work)
Try to save the file to C:\Users\username\My Documents\test.txt
If you really do want to save it to 'Documents' make sure the 'Documents' director exists.
If thats the case, open the properties on Documents under the security tab select Everyone under 'Group our user names' and 'Full control' under permissions. that will open it wide up and should allow file creation. you might want to take note of what the settings where so you can put them back as setting a directory to wide open permissions can be 'problematic'. try running the program again.

1
if you want write data to file just user any Writer For example:
FileWriter writer = new FileWriter(yourFile);
You can use stream filtering for faster action.
Show more your code. You've just showed condition for existing file.
2
if you want create file in Documents folder, get a path, then make a:
File file = new File(documentPath);
while(!file.exists())
file.createNewFile();
//condition for file existing...`
If I don't help, comment below, just I can't understand your question :). Good Luck

Related

Android Studio cannot read from file, does not exist

I'm trying to read from a file in Android Studio, in a small Java app. So I'm trying this:
File test = new File("C:\\testing\\testFile.dat");
if (test.exists()) {
System.out.println("test exists");
}
else {
System.out.println("test doesn't exist");
}
The file definitely exists, but it keeps on reporting that the file doesn't exist. I was able to work around this with another file by using the AssetManager and reading it through a stream, but the method I'm calling now requires a File's absolute path, but it's point blank refusing to find the file.
Am I doing something dumb, or misunderstanding something?
UPDATE
Ok, thanks for the input, I've now solved the problem. First I had to upload the file I wanted into the virtual device's storage, then I was able to get the path to it.
File test = new File(this.getFilesDir().getAbsolutePath(), "testFile.dat");
but the method I'm calling now requires a File's absolute path
Assets are files on your development machine. They are not files on the device.
Ideally, you switch to some library that supports InputStream or similar options, rather than requiring a filesystem path. If that is not an option, you can always get the InputStream from AssetManager and use that to make a copy of the data in some file that you control (e.g., in getCacheDir()). You can then pass the path to that file to this method.
You can place this file in your assets/ folder inside the android project and access using the following code.
val inputSteam = assets.open("testFile.dat")
or place it inside the res/raw folder and access it like below.
val inputStream = resources.openRawResource(R.raw.testFile)
We can't access a file on a development machine like this and won't be available on an android device so it will break so it's better if we move this somewhere inside the project and access it as above.

Passing a .JAR program (ran from terminal) a text file as input

I have created a java program that other testers will use to help with their testing. I will be sending them a zip file with the .jar, a readme.txt, and main.properties.txt file.
The main.properties.txt file is a template for the testers to input their DB access credentials. They will update the main.properties file with their db cred's and then attempt to run the .jar from the terminal or command line. The issue I am running into is this. My program needs this updated main.properties.txt file so it can create the connections to our DB's.
What instructions do I need to give in my readme so my program can successfully find the main.properties.txt? Does the main.properties need to be in the same directory as the .jar? Can the testers just create a file on their desktop or documents folders to put the .jar and main.props?
The other question I have is how do I pass this file to my program once its ran from the terminal? Currently it is really easy, because the main.props is part of my program and I can just do something like
Properties prop = new Properties();
FileInputStream in = new FileInputStream("src/main/resources/main.properties");
prop.load(in);
in.close();
But now main.properties is not part of the project anymore. I don't know how to change the code above so that it can find the text from a directory on the local. The location in which they wish to put their main.properties is out of my control so writing a static path will not work. Please help!
There are many ways, I'll show you two.
You need a File object that points to the main.properties file. Then you create a stream on this object new FileInputStream(File) , as you already did by using a String.
The problem of course is to get a relative path to main.properties.txt which works on all systems, regardless where the jar-File is located.
1. Desktop
In this case the main.properties.txt is located at the users desktop. Here is how you access it:
File desktop = new File(System.getProperty("user.home"), "Desktop");
File target = new File(desktop, "main.properties.txt");
Alernativly, if you plan to distribute configuration and property files that do not require user interaction, you may want to use locations like Temp or Documents (Windows).
2. Relative to the jar
Probably one of your best options. Assume the target is in the same folder than the jar-File (or at least in a fix structure relative to the jar). Here is how you access it (related question: how-to-get-the-path-of-a-running-jar-file):
CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
File jarDir = jarFile.getParentFile();
File target = new File(jarDir, "main.properties.txt");

Why is a file being saved to a different directory path in NetBeans?

For some unusual reason, when I am using FileWriter for Java Netbean, the file gets written into this directory:
C:\Users\myname\AppData\Roaming\NetBeans\7.2\config\GF3\domain1
rather than to my working directory, which is at the desktop.
I used this code to check my User Directory, and it returns this:
System.out.println(System.getProperty("user.dir"));
INFO: C:\Users\myname\AppData\Roaming\NetBeans\7.2\config\GF3\domain1
which is obviously NOT my working directory where my source code is. I thought I could have accidentally configured Netbeans to change the directory, but I checked through NetBeans menu and can't figure out how to undo this.
I have never had this problem before in my previous projects. As simple as the following code, the file should appear in my working directory.
File file = new File("myFile.xml");
Instead now I'm being forced to enter the path name to make the file save into my working directory, which is not going to be dynamic if I change computer.
String dir = "C:\\Users\\myname\\Desktop\\Assignment\\IRAssignmentJ\\";
File file = new File(dir + "myFile.xml");
Please enlighten me how do I solve this.
rather than to my working directory, which is at the desktop
No it isn't. The current working directory is whereever the file got saved, by definition. If Netbeans chooses to change directory to where it was saved, there's nothing you can do about it. If you want it in your home directory, there is a system property for that. If you want it saved somewhere else, use a full pathname.
But the behaviour of the application under Netbeans is of little interest. What matters is when you run it as though standalone, like a customer would.

Permissions and File.renameTo in Java 6 strange behavior

I have a Java program (running under Java 6), that monitors a directory parses the name of found files and runs actions (including copying the file) according to meta data and file content then, depending on the success or failure of the process, moves the files to a OK or KO directory.
I run my program as a simple user.
I tried, for the test, to put files belonging to root in my monitored directory.
Furthermore, I gave them 000 permissions.
The program would find the files but fail on the copy of the file.
For the record, the actual copy is done on this model:
FileOutputStream fos = new FileOutputstrem(DestFile)
FileInputStream stream = new FileInputStream(File);
byte buffer[] = new byte[bufferSize];
int nbRead;
while (-1 != (nbRead = fin.read(buffer)))
fos.write(buffer, 0, nbRead);
So far, seeing the program fail is exactly what I expected, 000 permissions on a un-owned file, that cannot be read.
But what is strange is that my files were moved to the KO box.
The move is done with
File failedFileName = new File(KOdirectory, myFile.getName());
myFile.renameTo(failedFileName);
Should that work? (given they are onwed by root and with 000 permissions)?
They end up in the KO directory, still owned by root with 000 permissions.
When I add read permissions (so my files are 444 root-owned) and reinject them into the monitored folder, the whole process runs smoothly and files end up in the OK directory (still root-owned and 444 permissions).
How is it possible to move files on which one has only reading rights?
How does this reading, moving, deleting works depending on the OS? on the distro?
Maybe I should add I run this on Ubuntu whose awkward root user (it exists, but not completely) concept might be messing with this.
Moving and renaming files does nothing to the file contents; instead, it changes the directory entries. So you need write permission on the directory, not the file itself.
Try it: if you remove the write permission to the directory, and give write permission to the file, you won't be able to rename or move the file anymore.
There are commands like mv or rm that actually check the file permission, and ask for confirmation if you want to move or change them. But that's extra code in the command and does not come from the operating system itself.
This is the same on all linux/unix systems. Reading/changing a file's content checks the permissions on the file; changing the file name or moving it to a different directory checks the permissions on the directory(/ies). This does not depend on the distro, it's the same on all linux systems, as well as Solaris, AIX, HP/UX and what other commercial unixes there are.
Moving a file from one directory to another only requires modification of directory entries for the directories in question. This means that you need only write and search permissions to the directories. The permissions or the owner of the file being moved do not matter.
You can read more about this in the appropriate man pages, such as the page for rename(2) and path_resolution(7).
A file has permission and this determines if you can read, modify or execute this file.
A file exists in one or more directories and it is the permission of the directory, not the file, which determines if the directory can be listed, modified or used.
So when you move a file, you are changing the directory, not the file.

Can't find folder or file created with Android App with windows file exlorer

I'm creating a directory and a text file on the sdcard in one of my apps because I want to be able to move it to my computer for analysis. But I can't find the folder or the file I'm creating on my sdcard using the file browser on my computer.
I CAN find and read the file using my phones file manager but not using the file browser in windows.
So the file and folder are succesfully created and I can write to the file, I can also find and read the file using the file manager on my phone but I can't find either directory or file using my computer.
I have a uses permission for the application to allow it to write to external storage.
This is the code I use to create the file and directory.
String fileName = "testFil.txt";
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/PulsApp";
File appDirectory = new File(path);
appDirectory.mkdirs();
File file = new File(path, fileName);
try {
file.createNewFile();
} catch (IOException e) {
}
Does anyone know what the problem is and how to fix it? I really need to be able to write files to my sdcard so I can transfer them to my computer.
I am completely baffled by this problem since all the research I've done point to that everyone else is doing the same thing.
If your device is running Android 3.0 or higher, you also need to use MediaScannerConnection to index your newly-created file before it will show up on a development PC's file explorer.
More accurately, the newly-created file needs to be indexed by the MediaStore. That will eventually happen for other reasons (e.g., device reboot). However, you are better served using scanFile() on MediaScannerConnection to get it to happen more quickly.
I blogged about this last summer.
Sometimes that the MediaScannerConnection will recognize the folder as a unknown type file, so try to create another folder inside the original one can avoid this problem.
I have met the same problem, and I use the method in the comment
And it works for me.

Categories