i am aware i am asking somethink that cannot be done without manually looping over the file system. But maybe someone have a better idea then mine.
i have a list of users and just one of them has in his own folder the file aaa.xml
from the linux shell of course if i type
vi /user/*/aaa.xml
i can open the file. I would like to use the same future in java but it seams not to Work
File designFile = new File("/user/*/aaa.xml");
solution would be to try to locate the file in each of the users directory but it seams not to nice. do you guys have a better idea??
cheers,
Ste
This might be related to what you are looking for. Hope it helps.
A FileSet package/class wanted for Java
Edit:
Then how about this?
How to find files that match a wildcard string in Java?
well.. seams not feasible because cannot work over different Operating systems.
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
String filePath = absolutePath.
substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("File path : " + filePath);
Related
So, I'm creating a game and need to create directories to store all the user's data and saves and whatnot. As you can see, I need to create a folder in the Application Data folder of the user called, "[WarDungeon]", and there, I will store other folders for such data like levels, the bin, sprites, etc.
I am not too interested in working with Mac OS and Linux as I want to get the %appdata% folder working with Windows to begin with.
Here's my code:
public FileManage() {
gamePath = System.getenv("APPDATA") + "[WarDungeon]";
gameLevelPath = System.getProperty("user.home") + "\\Local Settings\\ApplicationData\\[WarDungeon]\\level";
gameBinPath = System.getProperty("user.home") + "\\Local Settings\\ApplicationData\\[WarDungeon]\\bin";
File createDir1 = new File(gamePath);
createDir1.mkdir();
System.out.println("First test passed.");
if (createDir1.exists() == true) {
System.out.println("First directory created!");
}
}
How do I fix this?
Thanks in advance, :)
I realize that this question is two years old, but since this is the first result while googling "java store in appdata", I decided to add a correct answer for future googlers.
The question is tagged with Java, and the OP posted Java code, but the accepted answer is .NET (not Java).
Quoted directly from this answer:
System.getenv("APPDATA")
This will give the location to the user's AppData folder (in Windows). You can get a result similar to what the OP wanted by doing the following:
File characterFolder = new File(System.getenv("APPDATA") + "\\" + characterName);
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
I am having a little issue trying to figure out the best solution to the my path problems. I am running a java test that I want to get two things.
The absolute location of the project
The absolute location to the current class file that is running
I want to proper / or \ being on the OS version so the folder structure stays intact. I am currently using this but it is not exactly what I am looking for
final String parentDir = System.getProperty("user.dir");
final String path = "src/test/java/" + method.getDeclaringClass()
.getCanonicalName().replaceAll("\\.", "/") + ".java";
Any help would be appreciated. Thanks
Update: I am trying to get the url of the precompiled code as I need access to the comments in the code. This may change some of your guys answers
Update 2: Ok I got it to work.
final String path = new File(getClass().getResource("/").getFile())
.getParent().split("target")[0] + "src/test/java/" + method
.getDeclaringClass().getCanonicalName()
.replaceAll("\\.", "/") + ".java";
Thanks Guys
Given that you are calling this from MyClass you should call
File directory = (new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())).getParentFile();
I had the same question once. In addition to Jatin's answer I had to add an toURI() to get the correct path on all platforms (Windows, etc.) and post 1.5 JVMs.
If say you are running from jar file:
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent()+"/"
returns the folder containing the jar file.
Remove the .getParent() above to get path to the exact class file
Because I asked wrong question last time, I want to correct my intention. How can I find file by name in specified folder? I have a variable with a name of this file and i want to find it in specified folder. Any ideas?
Maybe the simplest thing that works is:
String dirPath = "path/to/directory";
String fileName = "foo.txt";
boolean fileExistsInDir = new File( dirPath, fileName ).exists();
File is just a placeholder for a location in the file system. The location does not have to exist.
Use Finding files in Java as a starting point. It should have everything that you are looking for - ask another specific question if you get stuck.
I am making a project for college and have made a program which creates csv files. I would like there to be a button which you can click which then opens the csv file with excel. Thanks
Knowing that MsOffice is installed on the system, you should be able to open a document with it from command line using the command
excel myDoc.csv
to execute such a command from java, you could use this snapshot:
File myCSVFile; //reference to your file here
String execString = "excel " + myCSVFile.getAbsolutePath();
Runtime run = Runtime.getRuntime();
try {
Process pp = run.exec(execString);
} catch(Exception e) {
e.printStackTrace();
}
This is somewhat rough and needs styling, of course, but generally it should work. Besides, to be more graceful you could also check Windows registry, using the java.util.prefs.Preferences class, to know if MsOffice is installed and, if yes, where. But, please, be aware, if you are reckoning for MsExcel (as I understood from your post), this will automatically cancel Java's multiplatform approach. Hopefully, this helps :)
If you are using Java 6 you can use the Desktop class. Read also Opening, Editing, and Printing a File
You can use JExcel API. It will be very easy for you.
For whatever reason, execString's provided did not work for me, but the one below worked:
String execString = "cmd /c start excel \"" + filePathString + "\"";
With the other exeString's I kept getting an exception saying that the runtime cannot find the file - start or excel.
I am trying to copy a file using the following code:
File targetFile = new File(targetPath + File.separator + filename);
...
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, i);
}
For some users the targetFile.createNewFile results in this exception:
java.io.IOException: The filename, directory name, or volume label syntax is incorrect
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:850)
Filename and directory name seem to be correct. The directory targetPath is even checked for existence before the copy code is executed and the filename looks like this: AB_timestamp.xml
The user has write permissions to the targetPath and can copy the file without problems using the OS.
As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.
This can occur when filename has timestamp with colons, eg. myfile_HH:mm:ss.csv Removing colons fixed the issue.
Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename:
File targetFile = new File(targetPath, filename);
I just encountered the same problem. I think it has to something do with write access permission. I got the error while trying to write to c:\ but on changing to D:\ everything worked fine.
Apparently Java did not have permission to write to my System Drive (Running Windows 7 installed on C:)
Here is the test program I use
import java.io.File;
public class TestWrite {
public static void main(String[] args) {
if (args.length!=1) {
throw new IllegalArgumentException("Expected 1 argument: dir for tmp file");
}
try {
File.createTempFile("bla",".tmp",new File(args[0]));
} catch (Exception e) {
System.out.println("exception:"+e);
e.printStackTrace();
}
}
}
Try to create the file in a different directory - e.g. "C:\" after you made sure you have write access to that directory. If that works, the path name of the file is wrong.
Take a look at the comment in the Exception and try to vary all the elements in the path name of the file. Experiment. Draw conclusions.
Remove any special characters in the file/folder name in the complete path.
Do you check that the targetPath is a directory, or just that something exists with that name? (I know you say the user can copy it from the operating system, but maybe they're typing something else).
Does targetPath end with a File.separator already?
(It would help if you could log and tell us what the value of targetPath and filename are on a failing case)
Maybe the problem is that it is copying the file over the network, to a shared drive? I think java can have problems when writing files using NFS when the path is something like \mypc\myshared folder.
What is the path where this problem happens?
Try adding some logging to see exactly what is the name and path the file is trying to create, to ensure that the parent is well a directory.
In addition, you can also take a look at Channels instead of using a loop. ;-)
You say "for some users" - so it works for others? What is the difference here, are the users running different instances on different machines, or is this a server that services concurrent users?
If the latter, I'd say it is a concurrency bug somehow - two threads check try to create the file with WinNTFileSystem.createFileExclusively(Native Method) simultaniously.
Neither createNewFile or createFileExclusively are synchronized when I look at the OpenJDK source, so you may have to synchronize this block yourself.
Maybe the file already exists. It could be the case if your timestamp resolution is not good enough. As it is an IOException that you are getting, it might not be a permission issue (in which case you would get a SecurityException).
I would first check for file existence before trying to create the file and try to log what's happening.
Look at public boolean createNewFile() for more information on the method you are using.
As I was not able to reproduce the error on my own machine or get hands on the machine of the user where the code failed I waited until now to declare an accepted answer.
I changed the code to the following:
File parentFolder = new File(targetPath);
... do some checks on parentFolder here ...
File targetFile = new File(parentFolder, filename);
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, i);
}
After that it worked for the user reporting the problem.
So it seems Alexanders answer did the trick - although I actually use a slightly different constructor than he gave, but along the same lines.
I yet have to talk that user into helping me verifying that the code change fixed the error (instead of him doing something differently) by running the old version again and checking if it still fails.
btw. logging was in place and the logged path seemed ok - sorry for not mentioning that. I took that for granted and found it unnecessarily complicated the code in the question.
Thanks for the helpful answers.
A very similar error:-
" ... java.io.IOException: The filename, directory name, or volume label syntax is incorrect"
was generated in Eclipse for me when the TOMCAT home setting had a training backslash.
The minor edit suggested at:-
http://www.coderanch.com/t/556633/Tomcat/java-io-IOException-filename-directory
fixed it for me.
FileUtils.copyFile(src,new File("C:\\Users\\daiva\\eclipse-workspace\\PracticeProgram\\Screenshot\\adi.png"));
Try to copy file like this.