I want to make a program that you can email to someone and they can run it.
Right now my code for making a file is like this:
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml);
f.createNewFile();
But what if someones username is not S0urceC0ded, or they put the project in a different place? How could I set the file path to the src folder plus the filename?
Leave the path off entirely, it will use the directory of the project.
Change
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml");
To
File f = new File("axmlfile.xml");
I generally use code like this for temporary file storage, this way it gets cleaned up when the application finishes. If required you can allow the user to save a version of the file or move it to a permanent location.
try{
//create a temporary file
File temp = File.createTempFile("axmlfile", ".xml");
System.out.println("Location: " + temp.getAbsolutePath());
}catch(IOException e){
e.printStackTrace();
}
Related
So with the code below it creates the file in the folder
File f = new File(path);
if(!f.exists())
f.mkdirs();
, but i only want to create the directory, because after this i use this code
file.transferTo(new File(path));
which saves a Multipart file to the same location, but it throws and error because there is already a file. Is there a way only to create the folder without the file ? One solution is to delete the first file, but looking for better solution
EDIT:
File f = new File(path);
this line creates the folders and the file, it shouldn't. I use java 8 and IntelliJ 14
SOLUTION:
The problem was Intellij or Intellij debug watches. After restarting it and clearing watches which were like:
new File(path)
file.transferTo(new File(path))
f.exists()
The code started working.
It should be
f.getParentFile().mkdirs();
You don't need to check for existence beforehand: mkdirs() already does that.
File dir = new File("<Your_Path>/TestDirectory");
// attempt to create the directory here
boolean successful = dir.mkdir();
if (successful)
{
// creating the directory succeeded
System.out.println("directory was created successfully");
}
else
{
// creating the directory failed
System.out.println("failed trying to create the directory");
}
You can create your files inside your directory path from then on....
I have create folder (i.e uploads ) in web application. I want to create one more folder inside "uploads" folder at runtime depends one the username of user. for this i have write below code. This code is creating folder and file but the location is different that i expected.
the location that i am getting is in eclipse location not web application location
D:\PAST\RequiredPlugins\JUNO\eclipse\uploads\datto\adhar.PNG
then i am getting error in FileOutStream that "system can't find the location specified."
public String getFolderName(String folderName, MultipartFile uploadPhoto)
throws ShareMeException {
File uploadfFile = null;
try {
File file = new File("uploads\\" + folderName);
if (!file.exists()) {
file.mkdir();
}
uploadfFile = new File(file.getAbsoluteFile()
+ "\\"+uploadPhoto.getOriginalFilename());
if (uploadfFile.exists()) {
throw new ShareMeException(
"file already exist please rename it");
} else {
uploadfFile.createNewFile();
FileOutputStream fout = new FileOutputStream(uploadfFile);
fout.write(uploadPhoto.getBytes());
fout.flush();
fout.close();
}
} catch (IOException e) {
throw new ShareMeException(e.getMessage());
}
return uploadfFile.getAbsolutePath();
}
i want to save uploaded file in web app "uploads" folder
Your filename is not absolute: uploads\folderName is resolved against the current directory, which the Eclipse launcher sets to JUNO\eclipse.
You should introduce an application variable like APP_HOME and resolve any data directory (including upload) against this variable.
Also, I suggest not to name anything (neither files nor directories) on your filesystem after user-entered input: you are asking for troubles (unicode characters in the user name) and especially security holes (even in combination with the unicode thing). If you really want to use the filesystem, keep the filename anonymous (1.data, 2.data, ...) and keep metadata inside some database.
You can do something on below lines in your webapp:-
String folderPath= request.getServletContext().getRealPath("/");
File file = new File (folderPath+"upload");
file.mkdir();
I am trying to create a file named VirtualATM.txt in a given directory if it does not already exist, if it does exist it shouldn't do anything to do the file and just continue. I am finding that with my code, whether the file exists or not, it is wiping the data inside the file and re-creating it every time I run it. The code I used to do this is below:
try{
String DirToWriteFile = System.getProperty("user.dir") + "/VirtualATM.txt"; //Get path to write text file to.
DirToWriteFile.trim();
File file = new File(DirToWriteFile);
if (!file.exists()) {
file.createNewFile();
}catch(IOException e){
e.printStackTrace();
}
Can anyone tell me why this happens?
Here
if (!file.exists() && file.isDirectory())
you are checking that if file exits and it should not be directory. No need for this if you want to just check if file exists
just use
if (!file.exists)
I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.
In the same directory there is the .class file compiled for the following code:
try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
System.out.println(e);
}
Debugging the code (breakpoint in "Scanner sc ..") an exception is launched and the following is printed:
java.io.FileNotFoundException: file.txt (the system can't find the
specified file)
I also tried using "/file.txt" and "//file.txt" but same result.
Thank you in advance for any hint
If you just use new File("pathtofile") that path is relative to your current working directory, which is not at all necessarily where your class files are.
If you are sure that the file is somewhere on your classpath, you could use the following pattern instead:
URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
The JVM will look for the file in the current working directory.
Where this is depends on your IDE settings (how your program is executed).
To figure out where it expects file.txt to be located, you could do
System.out.println(new File("."));
If it for instance outputs
/some/path/project/build
you should place file.txt in the build directory (or specify the proper path relative to the build directory).
Try:
File f = new File("./build/classes/file.txt");
Use "." to denote the current directory
String path = "./build/classes/file.txt";
File f = new File(path);
File Object loads, looking for match in its current directory.... which is Directly in Your project folder where your class files are loaded not in your source ..... put the file directly in the project folder
I am using:
// File (or directory) to be moved
File file = new File(output.toString());
// Destination directory
File dir = new File(directory_name);
// Move file to new directory
boolean success = file.renameTo(new File(dir, new_file.getName()));
if (!success) {
// File was not successfully moved
}
In this case file is main.vm, and folder is seven
the program shows that it works(the file exists and all) but the file is not moving to the seven directory.
Any ideas why?
Is it ok that the file name is main.vm or do i need to enter full path? the same for the folder.
Thanks
Maybe you wanna take a look at the Apache Commons FileUtils
Works for me. (run with java -ea opt.)
File f = new File("foo.mv");
if(!f.exists())
assert f.createNewFile() : "failed to create foo.mv";
File folder = new File("7");
if(!folder.exists())
assert folder.mkdir() : "failed to create new directory";
File fnew = new File(folder, f.getName());
assert !fnew.exists() : "fnew already exists";
f.renameTo(fnew);
assert fnew.exists() : "fnew does not exist -- move failed";
System.out.format("moved %s to %s\n",f, fnew);
Try to do following steps:
check if you move the file inside same filesystem - otherwise it will fail;
create destination directory;
define "new_file" variable.
You need to enter full path of the file, not only the filename. And would be nice if you'll show up your full source code in the future, for better understanding/answers.