import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;`enter code here`
public class Mover {
public static void main(String[] args) throws IOException, InterruptedException {
URL source = Mover.class.getResource("host");
source.toString();
String destino = "C:\\users\\jerso\\desktop\\";
Path sourceFile = Paths.get(source,"hosts");//here an error occurs.
Path targetFile = Paths.get(destino,"hosts");
Files.copy(sourceFile, targetFile,StandardCopyOption.REPLACE_EXISTING);
enter code here
}
}
I Don't know what to do here->>Path sourceFile = Paths.get(source,"hosts");
The method get(String, String...) in the type Paths is not applicable for the arguments (URL, String.
The target could be composed as:
Path targetFile = Paths.get("C:\\users\\jerso\\desktop", "hosts");
Solution:
URL source = Mover.class.getResource("host/hosts");
Path sourceFile = Paths.get(source.toURI());
Files.copy(sourceFile, targetFile,StandardCopyOption.REPLACE_EXISTING);
Better (more immediate):
InputStream sourceIn = Mover.class.getResourceAsStream("host/hosts");
Files.copy(sourceIn, targetFile,StandardCopyOption.REPLACE_EXISTING);
Mind that getResource and getResourceAsStream use relative paths from the package directory of class Mover. For absolute paths: "/host/hosts".
Calling toString() on source does not change the memory reference to now point to a string; toString() returns a string. What you're looking for is this:
Path sourceFile = Paths.get(source.toString(),"hosts");
Good luck!
Related
SO, from what I've gathered, one is supposed to be able to create a filesystem from a zip from java 7 and beyond. I'm trying this, the ultimate goal is to use the File object and access these files, just as if I accessed an unzipped file.
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class MainZipTest {
public static void main(String[] args) throws IOException, URISyntaxException {
Map<String, String> env = new HashMap<>();
env.put("read", "true");
File file = new File("C:/pathtoazip/data.zip");
URI uri = file.toURI();
String path = "jar:" + uri;
FileSystem fs = FileSystems.newFileSystem(URI.create(path), env);
for (Path p : fs.getRootDirectories()) {
System.out.println("root" + p);
//says "/"
System.out.println(new File(p.toString()).exists());
for (File f : new File(p.toString()).listFiles())
System.out.println(f.getAbsolutePath());
//lists the contents of my c drive!
}
System.out.println(new File("somefile.txt").exists());
System.out.println(fs.getPath("somefile.txt").toFile().exists());
System.out.println(new File("/somefile.txt").exists());
System.out.println(fs.getPath("/somefile.txt").toFile().exists());
}
}
it all prints "false". What am I doing wrong here? Or am I wrong in my assumption that I can access these files through the File object? If so, how does one access them?
Path was introduced as generalization of File (disk file). A Path can be inside a zip file, an URL, and more.
You can use Files with Path for similar File functionality.
for (Path p : fs.getRootDirectories()) {
System.out.println("root: " + p);
System.out.println(Files.exists(p));
Files.list(p).forEach(f -> System.out.println(f.toAbsolutePath()));
}
Note that a Path, like from a zip will maintain its actual file system view (fs, the zip).
So avoid File.
In my program I have the conversion as illustrated by the test.
Path->File->URI->URL->File.
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
#RunWith(JUnit4.class)
public class UrlStuffTest {
#Test
public void testFileToUriToUrlWithCreateFile() throws MalformedURLException, IOException {
Path p = Paths.get("testfolder", "xmls");
File f = p.toAbsolutePath().toFile();
f.mkdirs();
System.out.println(f);
URI uri = f.toURI();
System.out.println(uri);
URL url = uri.toURL();
System.out.println(url);
File aXmlFile = new File(url.getPath(), "test.xml");
System.out.println(aXmlFile);
aXmlFile.createNewFile();
}
#Test
public void testFileToUriToUrlWithCreateFileAndSpaceInPath() throws MalformedURLException, IOException {
Path p = Paths.get("test folder", "xmls");
File f = p.toAbsolutePath().toFile();
f.mkdirs();
System.out.println(f);
URI uri = f.toURI();
System.out.println(uri);
URL url = uri.toURL();
System.out.println(url);
File aXmlFile = new File(url.getPath(), "test.xml");
System.out.println(aXmlFile);
aXmlFile.createNewFile();
}
}
If you run the methods you will see that the upper one succeeds. The last one has a space in the path and fails on the last line basically saying "System can not find path...".
Output of the first method is
C:\Development\Workspace\spielwiese\testfolder\xmls
file:/C:/Development/Workspace/spielwiese/testfolder/xmls/
file:/C:/Development/Workspace/spielwiese/testfolder/xmls/
C:\Development\Workspace\spielwiese\testfolder\xmls\test.xml
Output of the second method is
C:\Development\Workspace\spielwiese\test folder\xmls
file:/C:/Development/Workspace/spielwiese/test%20folder/xmls/
file:/C:/Development/Workspace/spielwiese/test%20folder/xmls/
C:\Development\Workspace\spielwiese\test%20folder\xmls\test.xml
So when converting from File to URI the space becomes a %20. I guess this is what makes the final XML file creation fail.
I solved this issue in my program by skipping the conversion from File to URI by using File.toURL() method. This method is deprecated though.
What would be a better solution?
You need to decode the URL string before using it as File path. Something like this
String decodedUrlPath = java.net.URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8.name());
Really weird. With Path-File and without URL/URI it runs fine. Was trying to find other hints, but stuck on this one also:
Path path = Paths.get("test folder\\xmls", "test1.xml");
File aXmlFile = path.toFile();
System.out.println(aXmlFile);
aXmlFile.createNewFile();
So I guess in your URI you have to replace %20 pack to spaces " ".
That code works:
aXmlFile = new File(url.getPath().replaceAll("%20", " "), "test.xml");
System.out.println(aXmlFile);
aXmlFile.createNewFile();
It is possible to update individual files in a JAR file using the jar command as follows:
jar uf TicTacToe.jar images/new.gif
Is there a way to do this programmatically?
I have to rewrite the entire jar file if I use JarOutputStream, so I was wondering if there was a similar "random access" way to do this. Given that it can be done using the jar tool, I had expected there to be a similar way to do it programmatically.
It is possible to update just parts of the JAR file using Zip File System Provider available in Java 7:
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
public class ZipFSPUser {
public static void main(String [] args) throws Throwable {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// copy a file into the zip file
Files.copy( externalTxtFile,pathInZipfile,
StandardCopyOption.REPLACE_EXISTING );
}
}
}
Yes, if you use this opensource library you can modify it in this way as well.
https://truevfs.java.net
public static void main(String args[]) throws IOException{
File entry = new TFile("c:/tru6413/server/lib/nxps.jar/dir/second.txt");
Writer writer = new TFileWriter(entry);
try {
writer.write(" this is writing into a file inside an archive");
} finally {
writer.close();
}
}
I have to move files from one directory to other directory.
Am using property file. So the source and destination path is stored in property file.
Am haivng property reader class also.
In my source directory am having lots of files. One file should move to other directory if its complete the operation.
File size is more than 500MB.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import static java.nio.file.StandardCopyOption.*;
public class Main1
{
public static String primarydir="";
public static String secondarydir="";
public static void main(String[] argv)
throws Exception
{
primarydir=PropertyReader.getProperty("primarydir");
System.out.println(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
File dir = new File(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
String[] children = dir.list();
if (children == null)
{
System.out.println("does not exist or is not a directory");
}
else
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(filename);
try
{
File oldFile = new File(primarydir,children[i]);
System.out.println( "Before Moving"+oldFile.getName());
if (oldFile.renameTo(new File(secondarydir+oldFile.getName())))
{
System.out.println("The file was moved successfully to the new folder");
}
else
{
System.out.println("The File was not moved.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("ok");
}
}
}
My code is not moving the file into the correct path.
This is my property file
primarydir=C:/Desktop/A
secondarydir=D:/B
enter code here
Files should be in B drive. How to do? Any one can help me..!!
Change this:
oldFile.renameTo(new File(secondarydir+oldFile.getName()))
To this:
oldFile.renameTo(new File(secondarydir, oldFile.getName()))
It's best not to use string concatenation to join path segments, as the proper way to do it may be platform-dependent.
Edit: If you can use JDK 1.7 APIs, you can use Files.move() instead of File.renameTo()
Code - a java method:
/**
* copy by transfer, use this for cross partition copy,
* #param sFile source file,
* #param tFile target file,
* #throws IOException
*/
public static void copyByTransfer(File sFile, File tFile) throws IOException {
FileInputStream fInput = new FileInputStream(sFile);
FileOutputStream fOutput = new FileOutputStream(tFile);
FileChannel fReadChannel = fInput.getChannel();
FileChannel fWriteChannel = fOutput.getChannel();
fReadChannel.transferTo(0, fReadChannel.size(), fWriteChannel);
fReadChannel.close();
fWriteChannel.close();
fInput.close();
fOutput.close();
}
The method use nio, it make use os underling operation to improve performance.
Here is the import code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
If you are in eclipse, just use ctrl + shift + o.
I am trying to retrieve the owner of a file, using this code:
Path file = Paths.get( fileToExtract.getAbsolutePath() );
PosixFileAttributes attr = Files.readAttributes(file, PosixFileAttributes.class); //line that throws exception
System.out.println(attr.owner.getName());
taken from oracle's page (http://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html)
but i always get a UnsupportedOperationException at the line i indicate above.
java.lang.UnsupportedOperationException
at sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:192)
at java.nio.file.Files.readAttributes(Files.java:1684)
I think that 'readAttributes' method is abstract and this cause the exception, but (if this is true) i don't know how to implement this method in order to give me the file attributes.
Does anyone know how to implement this method, or an alternative method (that is tested) to get the file owner?
Try this - works also on Windows
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.UserPrincipal;
public class FileOwner {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp");
FileOwnerAttributeView ownerAttributeView = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
UserPrincipal owner = ownerAttributeView.getOwner();
System.out.println("owner: " + owner.getName());
}
}
Use BasicFileAttributes instead.
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
Posix file attributes are not supported in Windows.
Here is is a sample for files permissions on UNIX/Linux platforms
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
class A {
public static void main(String[] args) throws Exception
{
//Make sure file exists e.g. Unix path structure
Path p = Paths.get("/a/b/Log.txt");
PosixFileAttributes posix = Files.readAttributes(p,
PosixFileAttributes.class);
//Set Permissions if needs be for the file Log.txt
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rw-r--r--");
Files.setPosixFilePermissions(p, perms);
//Output the various attributes of the file named Log.txt
System.out.println(posix.group());
System.out.println(posix.permissions());
System.out.println(posix.owner());
}
}