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.
Related
I am using the following code but I am not able to rename the file.There is no such file newname.txt in the system as well. I am using JRE6. Please help me out! Also I have tried to rename using Files class, That too isn't working.
File f1 = new File("oldname.txt");
File f2 = new File("newname.txt");
boolean b = f1.renameTo(f2);
The same code gets execute on SunOs UNIX but not on my windows 7. Why is it so ? Can I do something to execute it on my local machine?
File path to oldname.txt is not correct, Try giving the absolute path and check it works like "c:\oldname.txt"
File f1 = new File("c:\\oldname.txt");
File f2 = new File("c:\\newname.txt");
boolean b = f1.renameTo(f2);
at the end print the value of b
Ref: Rename a file using Java (edited little bit to fit your requirment)
File f1 = new File("oldname.txt");
File f2 = new File("newname.txt");
if (!f1.exists())
throw new java.io.FileNotFoundException("file not found");
if (f2.exists())
throw new java.io.IOException("file exists");
// Rename file (or directory)
boolean success = f1.renameTo(f2);
if (!success) {
// File was not successfully renamed
}
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
This is probably a very basic question but I tried various options and it didn't work out and hence requesting help. I want to create a file inside a specified directory. If the file already exists, I want to append data to it. Below is what I tried:
var DirectoryName: String = "LogFiles"
var dir: File = new File(DirectoryName);
dir.mkdir();
var ActorID: String = "1"
var FileName: String = DirectoryName + File.separator + "Actor_" + ActorID + ".log"
val FileObj: File = new File(FileName)
// FileObj.getParentFile().mkdirs();
// FileObj.createNewFile();
var FileWriterObj: FileWriter = null
var FileExistsFlag = 0
if (!FileObj.exists())
{
FileWriterObj = new FileWriter(FileObj.getName())
}
else
{
FileWriterObj = new FileWriter(FileObj.getName(), true)
FileExistsFlag = 1
}
var writer = new PrintWriter(FileWriterObj)
if(FileExistsFlag == 0)
writer.write("new file")
else
writer.append("appending to old file")
Internet search asks to use the below:
FileObj.getParentFile().mkdirs();
FileObj.createNewFile();
But it creates empty files inside the directory and creates new files outside the directory and appends to it. And also few posts suggests that there is no need to use createNewFile() to create a file.
I tried giving various path formats like below:
var DirectoryName: String = "../LogFiles"
var DirectoryName: String = "/home/ms/Desktop/Project/LogFiles"
But still it does not create the files inside the directory.
Can you please point me what I'm missing?
OS: Ubuntu 12.04
You should be using FileObj.getAbsolutePath, rather than FileObj.getName. getName just returns the name of the file, which explains why it was always being placed in the current directory.
The empty files issue could be solved by calling writer.close() at the end of your function. I don't think it's necessary to use createNewFile
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.
The Apache Commons VFS library appears to be unable to support special Windows folders (Network, recent, computer, libraries, etc).
File[] cbFolders = (File[])sun.awt.shell.ShellFolder.get("fileChooserComboBoxFolders");
and then converting them to FileObjects like so:
for(File f: cbFolders){
fileObjArray.add(mgr.resolveFile(f.getPath()));
}
It just doesn't work and all you get is the path name for its name.
The path of these files are like ::{20D04FE0-3AEA-1069-A2D8-08002B30309D}
Any help in getting this working would be appreciated. It looks like its most likely a bug in the library. Hopefully someone knows of a hack or such to get it working.
Edit:
I believe I was close when I created new shortcuts
try{
final File[] cbFolders = (File[])sun.awt.shell.ShellFolder.get("fileChooserComboBoxFolders");
String name = "";
File[] systemFiles = new File[cbFolders.length];
i =0;
for(File f: cbFolders){
name = f.getName();
if(name.startsWith("::{")){
name = name.substring(2);
System.out.println("converting: " + name);
String fileName = fileSystemView.getSystemDisplayName(f);
File file = new File("C:\\Users\\Daniel\\Desktop\\" + fileName + "." + name);
boolean success = false;
success = file.mkdir(); //returns false even if it works,
systemFiles[i] = file;
}else
systemFiles[i] = f;
i++;
}
list = new ArrayList<File>(Arrays.asList(systemFiles));
}catch(final Exception e){
...
}
It shows the correct icon and name and on Windows Explorer it opens correctly, but still with VFS it opens an empty folder.
There is no real support for those files. The main problem is that neither the Java File object treats them correctly (new File("::{20D04FE0-3AEA-1069-A2D8-08002B30309D}").toURI().toString() does not properly escape the colons) nor is Java or VFS knowing about :: as an absolute filesystem root. So you cannot transform them into a URI (required by resolveFile()) which keeps the special properties recognized by Windows.