Using jdk7, I am trying to use the java.nio.file.Files class to move an empty directory, let's say Bar, into another empty directory, let's say Foo
Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
Files.move(
source,
target,
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
After executing that code snippet, I expected that the Bar directory would be in the Foo directory (...\Foo\Bar). Instead it is not. And here's the kicker, it's been deleted as well. Also, no exceptions were thrown.
Am I doing this wrong?
NOTE
I'm looking for a jdk7-specific solution.I am also looking into the problem, but I figured I'd see if there was anyone else playing around with jdk7.
EDIT
In addition to the accepted answer, here's another solution
Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
Files.move(
source,
target.resolve(source.getFileName()),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
I didn't realize jdk7 java.nio.file.Files is a necessity, so here is the edited solution. Please see if it works coz I have never used the new Files class before.
Path source = Paths.get("Bar");
Path target = Paths.get("Foo", "Bar");
try {
Files.move(
source,
target,
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
In the javadoc for the Files.move method you will find an example where it moves a file into a directory, keeping the same file name. This seems to be what you were looking for.
Here is the solution.
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:
Path source = ...
Path newdir = ...
Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);
//Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
Related
This piece of code throws a FileNotFoundException, i'm sure the file exists in my working directory, am i doing something wrong?
private void generateInvoiceNumber(){ //uses reads previous invoice number and increments it.
try {
File invoiceFile = new File("./Invoices/invoiceFile.txt");
FileWriter writer = new FileWriter(invoiceFile,false);
Scanner getter = new Scanner(invoiceFile);
this.invoiceNumber = getter.nextInt();
writer.write(++invoiceNumber);
writer.close();
getter.nextInt();
getter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
My tip:
Print (in your code) the current path location.
Then you can use this path in order to find the exact path you should use in order to access your file.
Maybe you should put more concrete absolute path:
File invoiceFile = Paths.get ("C:","Invoices", "invoiceFile.txt").toFile();
or if you trying to get from current path:
File invoiceFile = Paths.get (".","Invoices", "invoiceFile.txt").toFile();
And you can check your . path:
System.out.println(new File(".").getCanonicalPath());
Which operating system you are using?
It’s better to use paths when you are constructing a path to your file like
File file = Paths.get (".","Invoices", "invoice.txt").toFile();
corrected " symbols and default root "." which is your folder where app started.
I have created a Zip file on a JimFS FileSystem instance. I would now like to read the Zip using the Java FileSystem API.
Here is how I create the FileSystem:
final FileSystem zipFs = FileSystems.newFileSystem(
source, // source is a Path tied to my JimFS FileSystem
null);
However, this throws an error:
java.nio.file.ProviderNotFoundException: Provider not found
Interestingly, the code works with the default FileSystem.
What does this error mean?
How should I create my Zip FileSystem?
This is not supported before JDK 12 via that specific constructor (Path, ClassLoader)
This was fixed in JDK12, with commit 196c20c0d14d99cc08fae64a74c802b061231a41
The offending code was in ZipFileSystemProvider in JDK 11 and earlier:
if (path.getFileSystem() != FileSystems.getDefault()) {
throw new UnsupportedOperationException();
}
This works, but it seems hacky and crucially I'm not sure why it works.
public static FileSystem fileSystemForZip(final Path pathToZip) {
Objects.requireNotNull(pathToZip, "pathToZip is null");
try {
return FileSystems.getFileSystem(pathToZipFile.toUri());
} catch (Exception e) {
try {
return FileSystems.getFileSystem(URI.create("jar:" + pathToZipFile.toUri()));
} catch (Exception e2) {
return FileSystems.newFileSystem(
URI.create("jar:" + pathToZipFile.toUri()),
new HashMap<>());
}
}
}
Check whether source path points to the zip archive file.
In my case it pointed to the ordinary text file which even had other than '.zip' extension.
Getting an error when trying to open a FileInputStream to load Map from file with .ser extension.
Constructor where I create new File and invoke method that loads map from file:
protected DriveatorImpl() {
accounts = new ConcurrentHashMap<String, Client>();
db = new File("database.ser"); // oddly this does not create a file if one does not exist
loadDB();
}
#SuppressWarnings("unchecked")
private void loadDB() {
try {
fileIn = new FileInputStream(db);
in = new ObjectInputStream(fileIn);
accounts = (Map<String, Client>) in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I've tried to create file manually and put it in same package with class, but it does not help. What's going on?!
Thank You!
You provide a relative path for the file. That means program will look for the file relative to the working directory.
Depending on how you run the program it will be the directory you run it from (if run from Shell/Cmd) or whatever is configured in the project settings (if run from the IDE). For the latter, it depends on the IDE but usually it's the project root directory.
More info on working directory: https://en.wikipedia.org/wiki/Working_directory
More info on relative path: https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths
Regarding creation of the file, it would create non-existing file if you were to write to it. When you read it, it expects it to exist. That means you have to create empty file (if one does not exist) before reading or simply treat exception as empty content.
The path to the file you have given might be wrong for IDE it can take relative path but from the command line, it will take the absolute path.
I've made this method that copies files from one absolute path (input directory) to another absolute path (output directory).
It doesn't give me any error, however no files are copied to the output folder.
Why would this be?
public static boolean copyFiles(String input, String output)
{
File source = new File(input);
File dest = new File(output);
try {
Files.copy(Paths.get(input), Paths.get(output), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
As #zapl said, Files.copy() only copies the directory.
I found the solution, by importing the Apache commons.io library.
org.apache.commons.io.FileUtils.copyDirectory(new File(input), new File(output));
This works.
For my case, the Files are copied, just that it is not shown in the project explorer (in Eclipse) so just refresh it will do.
Path FROM = Paths.get // need to get my file in my bin folder called s.txt, how would this be done?
Path TO = Paths.get("C:\\Temp\\to.txt");
try {
Files.copy(FROM, TO);
} catch (IOException e) {
e.printStackTrace();
}
Hi, I would really appreciate help, I basically need to get the path of a file located in my /bin/path
The local path to your project can be found using
System.getProperty("user.dir");
if your jar thats running is c:\workdir\myproject\bin\myproject.jar then System.getProperty("user.dir"); will return c:\workdir\myproject\bin
Heres how you could use it in your code...
Path FROM = Paths.get(System.getProperty("user.dir") + "/s.txt");
Path TO = Paths.get("C:\\Temp\\to.txt");
try {
Files.copy(FROM, TO);
} catch (IOException e) {
e.printStackTrace();
}
If I remember correctly, if using eclipse, go to:
project; properties; java build path; source; add folder - select bin folder
Then in your code do
Path TO = Paths.get(getClass().getResource("/bin/s.txt"));
Or you can defined the full system path from C:/ like your to path.