I created a desktop project in netbeans, in the project folder I have three files : file.txt, file2.txt and file3.txt, in the load of the program I want to call these three files, and this is the code I tried :
public void run() {
Path path = Paths.get("file.txt");
Path path2 = Paths.get("file2.txt");
Path path3 = Paths.get("file3.txt");
if(Files.exists(path) && Files.exists(path2) && Files.exists(path3)) {
lireFichiers();
}else{
JOptionPane.showConfirmDialog(null, "Files didn't found !");
}
}
but when I run my program I get the message : "Files didn't found !" which means he didn't found those files.
those files are created by this code :
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
The following three lines will only create file handlers for your program to use. This will not create a file by itself. If you are using the handler to write it will also create a file for you provided you close correctly after writing.
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
So, a sample code will look like:
File file = new File("Id.txt");
FileWriter fw = new FileWriter(file);
try
{
// write to file
}
finally
{
fw.close();
}
If the file is in the root of your project, this should work:
Path path = Paths.get("foo.txt");
System.out.println(Files.exists(path)); // true
Where exatlcy are the files you want to open in your project?
Please specify the language you use.
Generally you could search the file to see whether the files are in the program bootup folder. For webapps you should pay attention to the "absolute path and the relative path".
=========Edit============
If you are using Jave, then the file should be write out using FileWriter.close() before you can find them in your hard disk.
Ref
Thank you all for your help, I just tried this :
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
if(file.exists() && file2.exists() && file3.exists()){
// manipulation
}
and it works
Related
I am trying to create a temp file and generate a file name and then save a multipart file. I am using Spring Boot and the following code is working in local. But in heroku or docker it is throwing FileNotFoundException; So how to create a temp directory and save a file inside that temp directory in docker/heroku? Or what is the best way to save multipart file to temp folder in server? Anybody can help me? Thanks in advance.
File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");
if (!tempDirectory.exists()) {
tempDirectory.mkdir();
}
String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.pdf").getAbsolutePath();
File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")), "files");
if(tempDirectory.exists()){
System.out.println("something");
}else{
tempDirectory.mkdirs();
}
File file = new File(tempDirectory.getAbsolutePath()+"/abcd.txt");
if(!file.exists()){
file.createNewFile();
}
String file2= new File(tempDirectory.getAbsolutePath()+"/something.txt").getAbsolutePath();
System.out.println(file2);
Works totally fine at my end. The only problem you might be having is
String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.exe").getAbsolutePath();
This doesn't create the file in the temp directory you have created. It just returns the absolute path if it was to be saved in the directory mentioned. This might be the reason you are getting not found error. Try actually saving by using
file.transferTo(wherefileneedstobesavedlocation);
Below is my project like:
projectName
-package
- Util.java
- Test.json
In Util.java, I need to read the content from Test.json file and parse it.
Thus I use:
File currentfile = new File("");//get the current path
String absJsonPath = currentfile.getAbsolutePath() + "/Test.json";
While it did not work when I use a main method to test it. The thing is that the /src/package is lost in the obtained file path and I just got the path of the project.
And, when I deploy the project to weblogic server, I got another new error, the obtained current path is like:
.../DefaultDomain/.
I just want the file path in the file system, which is not related to the server.
What can I do for this? Thanks!
Put your file in resources folder and get it as following:
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("Test.json").getFile());
To read the content you can use following:
StringBuilder result = new StringBuilder("");
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
It's CanonicalPath() not Absolute. Check this out, let me know if it any helps.
Try this to get current path
String currentPath = System.getProperty("user.dir");
If you want to read a file in a specific package. You can use
File jsonFile = new File(getClass().getResource("/Test.json").getFile());
I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}
Here is what I wanna do:
Check if a folder exists
If it does not exists, create the folder
If it doest exists do nothing
At last create a file in that folder
Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code:
File folder = new File("D:\\temp");
if (folder.exists() && folder.isDirectory()) {
} else {
folder.mkdir();
}
String filePath = folder + File.separator;
File file = new File(filePath + "xxx.xml");
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
// more code here
Linux does not use drive letters (like D:) and uses forward slashes as file separator.
You can do something like this:
File folder = new File("/path/name/of/the/folder");
folder.mkdirs(); // this will also create parent directories if necessary
File file = new File(folder, "filename");
StreamResult result = new StreamResult(file);
You directory (D:\temp) is nos appropriate on Linux.
Please, consider using linux File System, and the File.SEPARATOR constant :
static String OS = System.getProperty("OS.name").toLowerCase();
String root = "/tmp";
if (OS.indexOf("win") >= 0) {
root="D:\\temp";
} else {
root="/";
}
File folder = new File(ROOT + "dir1" + File.SEPARATOR + "dir2");
if (folder.exists() && folder.isDirectory()) {
} else {
folder.mkdir();
}
Didn't tried it, but whould work.
D:\temp does not exists in linux systems (what I mean is it interprets it as if it were any other foldername)
In Linux systems the file seperator is / instead of \ as in case of Windows
so the solution is to :
File folder = new File("/tmp");
instead of
File folder = new File("D:\\temp");
Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class Files.
Consider both solutions using the getProperty static method of System class.
String os = System.getProperty("os.name");
if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0 ) // Unix
File folder = new File("/home/tmp");
else if(os.indexOf("win") >= 0) // Windows
File folder = new File("D:\\temp");
else
throw Exception("your message");
On Unix-like systems no logical discs. You can try create on /tmp or /home
Below code for create temp dirrectory in your home directory:
String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("user.home"):"D:\\";
System.out.println(myPathCandidate);
//Check write permissions
File folder = new File(myPathCandidate);
if (folder.exists() && folder.isDirectory() && folder.canWrite()) {
System.out.println("Create directory here");
} else {System.out.println("Wrong path");}
or, for /tmp - system temp dicecrory. Majority of users can write here:
String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("java.io.tmpdir"):"D:\\";
Since Java 7, you can use the Files utility class, with the new Path class. Note that exception handling has been omitted in the examples below.
// uses os separator for path/to/folder.
Path file = Paths.get("path","to","file");
// this creates directories in case they don't exist
Files.createDirectories(file.getParent());
if (!Files.exists(file)) {
Files.createFile(file);
}
StreamResult result = new StreamResult(file.toFile());
transformer.transform(source, result);
this covers the generic case, create a folder if it doesn't exist and a file on that folder.
In case you actually want to create a temporary file, as written in your example, then you just need to do the following:
// this create a temporary file on the system's default temp folder.
Path tempFile = Files.createTempFile("xxx", "xml");
StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE));
transformer.transform(source, result);
Note that with this method, the file name will not correspond exactly to the prefix you used (xxx, in this case).
Still, given that it's a temp file, that shouldn't matter at all. The DELETE_ON_CLOSE guarantees that the file will get deleted when closed.
I want to write a file results.txt to a specific directory on my machine (Z:\results to be precise). How do I go about specifying the directory to BufferedWriter/FileWriter?
Currently, it writes the file successfully but to the directory where my source code is located. Thanks
public void writefile(){
try{
Writer output = null;
File file = new File("results.txt");
output = new BufferedWriter(new FileWriter(file));
for(int i=0; i<100; i++){
//CODE TO FETCH RESULTS AND WRITE FILE
}
output.close();
System.out.println("File has been written");
}catch(Exception e){
System.out.println("Could not create file");
}
}
You should use the secondary constructor for File to specify the directory in which it is to be symbolically created. This is important because the answers that say to create a file by prepending the directory name to original name, are not as system independent as this method.
Sample code:
String dirName = /* something to pull specified dir from input */;
String fileName = "test.txt";
File dir = new File (dirName);
File actualFile = new File (dir, fileName);
/* rest is the same */
Hope it helps.
Use:
File file = new File("Z:\\results\\results.txt");
You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.
For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.
File file = new File("/home/userName/Documents/results.txt");
Just put the full directory location in the File object.
File file = new File("z:\\results.txt");
The best practice is using File.separator in the paths.