Does Files.copy(Path,Path) create directories? - java

I have a bunch of text files(say ss1.txt,ss2.txt,ss3.txt etc.) under a directory with my Java program (C:/Users/java/dir1)?
I want to move my txt files to a new directory that hasn't been created yet. I have a String address for all of my files and I think I can turn them into Paths using
Path path = Paths.get(textPath);
Would creating a String (C:/Users/java/dir2), turning that into a path using the above method and then using
Files.copy(C:/Users/java/dir1/ss1.txt,C:/Users/java/dir2)
result in ss1.text being copied to a new directory?

This is very easy with Files.createDirectories()
Path source = Path.of("c:/dir/dir-x/file.ext");
Path target = Path.of("c:/target-dir/dir-y/target-file.ext");
Files.createDirectories(target.getParent());
Files.copy(path, target, StandardCopyOption.REPLACE_EXISTING);
And do not worry if the directories already exist, in that case it will do nothing and keep going...

Method Files.copy(C:/Users/java/dir1/ss1.txt,C:/Users/java/dir2) will not create directory, it will create file dir2 in directory java that will contain ss1.txt data.
You could try it with this code:
File sourceFile = new File( "C:/Users/java/dir1/ss1.txt" );
Path sourcePath = sourceFile.toPath();
File destFile = new File( "C:/Users/java/dir2" );
Path destPath = destFile.toPath();
Files.copy( sourcePath, destPath );
Remember use java.nio.file.Files and java.nio.file.Path.
If you want to use class form java.nio to copy files from one directory to other you should use Files.walkFileTree(...) method. You can see solution here Java: Using nio Files.copy to Move Directory.
Or you can simply use `FileUtils class from apache http://commons.apache.org/proper/commons-io/ library, available since version 1.2.
File source = new File("C:/Users/java/dir1");
File dest = new File("C:/Users/java/dir2");
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}

Related

Unable to read resources from .jar [duplicate]

This question already has answers here:
Java Jar file: use resource errors: URI is not hierarchical
(6 answers)
Closed 6 years ago.
I have files in resource folder. For example if I need to get file from resource folder, I do like that:
File myFile= new File(MyClass.class.getResource(/myFile.jpg).toURI());
System.out.println(MyClass.class.getResource(/myFile.jpg).getPath());
I've tested and everything works!
The path is
/D:/java/projects/.../classes/X/Y/Z/myFile.jpg
But, If I create jar file, using , Maven:
mvn package
...and then start my app:
java -jar MyJar.jar
I have that following error:
Exception in thread "Thread-4" java.lang.RuntimeException: ხელმოწერის განხორციელება შეუძლებელია
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(File.java:363)
...and path of file is:
file:/D:/java/projects/.../target/MyJar.jar!/X/Y/Z/myFile.jpg
This exception happens when I try to get file from resource folder. At this line. Why? Why have that problem in JAR file? What do you think?
Is there another way, to get the resource folder path?
You should be using
getResourceAsStream(...);
when the resource is bundled as a jar/war or any other single file package for that matter.
See the thing is, a jar is a single file (kind of like a zip file) holding lots of files together. From Os's pov, its a single file and if you want to access a part of the file(your image file) you must use it as a stream.
Documentation
Here is a solution for Eclipse RCP / Plugin developers:
Bundle bundle = Platform.getBundle("resource_from_some_plugin");
URL fileURL = bundle.getEntry("files/test.txt");
File file = null;
try {
URL resolvedFileURL = FileLocator.toFileURL(fileURL);
// We need to use the 3-arg constructor of URI in order to properly escape file system chars
URI resolvedURI = new URI(resolvedFileURL.getProtocol(), resolvedFileURL.getPath(), null);
File file = new File(resolvedURI);
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
It's very important to use FileLocator.toFileURL(fileURL) rather than resolve(fileURL)
, cause when the plugin is packed into a jar this will cause Eclipse to create an unpacked version in a temporary location so that the object can be accessed using File. For instance, I guess Lars Vogel has an error in his article - http://blog.vogella.com/2010/07/06/reading-resources-from-plugin/
I face same issue when I was working on a project in my company. First Of All, The URI is not hierarichal Issue is because probably you are using "/" as file separator.
You must remember that "/" is for Windows and from OS to OS it changes, It may be different in Linux. Hence Use File.seperator .
So using
this.getClass().getClassLoader().getResource("res"+File.separator+"secondFolder")
may remove the URI not hierarichal. But Now you may face a Null Pointer Exception. I tried many different ways and then used JarEntries Class to solve it.
File jarFile = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
String actualFile = jarFile.getParentFile().getAbsolutePath()+File.separator+"Name_Of_Jar_File.jar";
System.out.println("jarFile is : "+jarFile.getAbsolutePath());
System.out.println("actulaFilePath is : "+actualFile);
final JarFile jar = new JarFile(actualFile);
final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
System.out.println("Reading entries in jar file ");
while(entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
final String name = jarEntry.getName();
if (name.startsWith("Might Specify a folder name you are searching for")) { //filter according to the path
System.out.println("file name is "+name);
System.out.println("is directory : "+jarEntry.isDirectory());
File scriptsFile = new File(name);
System.out.println("file names are : "+scriptsFile.getAbsolutePath());
}
}
jar.close();
You have to specify the jar name here explicitly. So Use this code, this will give you directory and sub directory inside the folder in jar.

finding path from directory present in jar

I am trying to use a jar file which itself is a web application in another web project. In my jar which i have created using eclipse's export to jar functionality, I have stored a directory.To access the files the from that directory i am using
BufferdReader tempDir = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(myDirPath),"UTF-8"));
// Then i iterate on tempDir
String line;
ArrayList<File> tempDirList = new ArrayList<File>();
int c = 0;
try {
while((line = tempDir.readLine())!= null)
{
File f = new File(line);
tempDirList.add(f);
c++;
}
} catch (IOException e)
{
e.printStackTrace();
}
Now on itrating on tempDirList when i try to read the file i need file path from which i get file but I did not get file path.
So i want to know that how i get file path?
You cannot access the files in the JAR as File objects since in the web container they might not get unpacked (so there is no file). You can only access them via streams as you did.
getClass().getResourceAsStream(myDirPath + "/file1.txt");
If you really need File objects (most of the times it's quite easy to avoid that), copy the files into temporary files which you then can access.
File tmp = File.createTemp("prefix", ".tmp");
tmp.deleteOnExit();
InputStream is = getClass().getResourceAsStream(myDirPath + "/file1.txt");
OutputStream os = new FileOutputStream(tmp);
ByteStreams.copy(is, os);
os.close();
is.close();
But as I said, using streams instead of file objects in the first place makes you more flexible.
If you really don't know all the files in the directory at compile time you might be interested in this answer to list contents.

Problem with moving a file to another 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.

How to read file from relative path in Java project? java.io.File cannot find the path specified

I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But I have this error:
The system cannot find the path specified
Can you give a solution to fix it?
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.
The relative path works in Java using the . specifier.
. means same folder as the currently running context.
.. means the parent folder of the currently running context.
So the question is how do you know the path where the Java is currently looking?
Do a small experiment
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.
For example if the output is
G:\JAVA8Ws\MyProject\content.
and your file is present in the folder "MyProject" simply use
File resourceFile = new File("../myFile.txt");
Hope this helps.
The following line can be used if we want to specify the relative path of the file.
File file = new File("./properties/files/ListStopWords.txt");
InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try .\properties\files\ListStopWords.txt
I could have commented but I have less rep for that.
Samrat's answer did the job for me. It's better to see the current directory path through the following code.
File directory = new File("./");
System.out.println(directory.getAbsolutePath());
I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.
./test/conf/appProperties/keystore
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
Assuming you want to read from resources directory in FileSystem class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading . is not needed.
I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :
Object obj = parser.parse(new FileReader("./src/command.json"));
For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem
For me it worked with -
String token = "";
File fileName = new File("filename.txt").getAbsoluteFile();
Scanner inFile = null;
try {
inFile = new Scanner(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( inFile.hasNext() )
{
String temp = inFile.next( );
token = token + temp;
}
inFile.close();
System.out.println("file contents" +token);
If text file is not being read, try using a more closer absolute path (if you wish
you could use complete absolute path,) like this:
FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");
assume that the absolute path is:
C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt
String basePath = new File("myFile.txt").getAbsolutePath();
this basepath you can use as the correct path of your file
if you want to load property file from resources folder which is available inside src folder, use this
String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();
p.load(resourceStream);
System.out.println(p.getProperty("db"));
db.properties files contains key and value db=sybase
If you are trying to call getClass() from Static method or static block, the you can do the following way.
You can call getClass() on the Properties object you are loading into.
public static Properties pathProperties = null;
static {
pathProperties = new Properties();
String pathPropertiesFile = "/file.xml";
// Now go for getClass() method
InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}

Getting the directory name in java

How do I get the directory name for a particular java.io.File on the drive in Java?
For example I have a file called test.java under a directory on my D drive.
I want to return the directory name for this file.
File file = new File("d:/test/test.java");
File parentDir = file.getParentFile(); // to get the parent dir
String parentDirName = file.getParent(); // to get the parent dir name
Remember, java.io.File represents directories as well as files.
With Java 7 there is yet another way of doing this:
Path path = Paths.get("d:/test/test.java");
Path parent = path.getParent();
//getFileName() returns file name for
//files and dir name for directories
String parentDirName = path.getFileName().toString();
I (slightly) prefer this way, because one is manipulating path rather than files, which imho better shows the intentions. You can read about the differences between File and Path in the Legacy File I/O Code tutorial
Note also that if you create a file this way (supposing "d:/test/" is current working directory):
File file = new File("test.java");
You might be surprised, that both getParentFile() and getParent() return null. Use these to get parent directory no matter how the File was created:
File parentDir = file.getAbsoluteFile().getParentFile();
String parentDirName = file.getAbsoluteFile().getParent();
File file = new File("d:/test/test.java");
String dirName = file.getParentFile().getName();
Say that you have a file called test.java in C:\\myfolder directory. Using the below code, you can find the directory where that file sits.
String fileDirectory = new File("C:\\myfolder\\test.java").getAbsolutePath();
fileDirectory = fileDirectory.substring(0,fileDirectory.lastIndexOf("\\"));
This code will give the output as C:\\myfolder

Categories

Resources