Get file owner metadata information with java - java

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());
}
}

Related

how convert here URL to String in java

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!

Include an exe-file into jar and run it

I tried to to include an exe-file into a jar-Application and to run it. The idea is to extract it temporary at first and then to run the temp-exe-file. How to do that? That is what I have tried. There is my code. It occurs the exception java.io.FileNotFoundException because of the source file "ffmpeg.exe". I verified, but the file is included and the directory is correct.
package extractffmpeg;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;
public class ExtractFFmpeg extends Application {
public void start(Stage primaryStage) throws IOException, URISyntaxException {
extractExe();
System.out.println("extract successfull");
Platform.exit();
}
public static void main(String[] args) {
launch(args);
}
public void extractExe() throws URISyntaxException, IOException{
final String resourcesPath = "ffmpeg/ffmpeg.exe";
URL url = ExtractFFmpeg.class.getResource(resourcesPath);
File source = new File(url.toString());
System.out.println("shows url of ffmpeg: " + url.getPath());
System.out.println("shows file of ffmpeg: " + source);
File destination = new File("C:/Users/FNI2Abt/Desktop/ffmpeg.exe");
FileUtils.copyFile(source, destination);
}
}
The idea is to create a self-extracting archive. The archive shall contain both JAR and EXE. The JAR file shall contain a class which would call Process.exec(...) on the adjacent EXE. Starting there, you can follow this tutorial:
How do I make a self extract and running installer

Can a Jar File be updated programmatically without rewriting the whole file?

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();
}
}

Java Creating files and directories with a certain owner (user/group) [duplicate]

This question already has answers here:
Change file owner group under Linux with java.nio.Files
(4 answers)
Closed 7 years ago.
Is possible in Java to manage creating files / directories (if program runs as ROOT) with different user/group ?
You can achieve JDK 7 (Java NIO)
Use setOwner() method....
public static Path setOwner(Path path,
UserPrincipal owner)
throws IOException
Usage Example: Suppose we want to make "joe" the owner of a file:
Path path = ...
UserPrincipalLookupService lookupService =
provider(path).getUserPrincipalLookupService();
UserPrincipal joe = lookupService.lookupPrincipalByName("joe");
Files.setOwner(path, joe);
Get more information about same from below url
http://docs.oracle.com/javase/tutorial/essential/io/file.html
Example : Set Owner
import java.nio.file.FileSystems;
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;
import java.nio.file.attribute.UserPrincipalLookupService;
public class Test {
public static void main(String[] args) throws Exception {
Path path = Paths.get("C:/home/docs/users.txt");
FileOwnerAttributeView view = Files.getFileAttributeView(path,
FileOwnerAttributeView.class);
UserPrincipalLookupService lookupService = FileSystems.getDefault()
.getUserPrincipalLookupService();
UserPrincipal userPrincipal = lookupService.lookupPrincipalByName("mary");
Files.setOwner(path, userPrincipal);
System.out.println("Owner: " + view.getOwner().getName());
}
}
Example : GetOwner
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 Test {
public static void main(String[] args) throws Exception {
Path path = Paths.get("C:/home/docs/users.txt");
FileOwnerAttributeView view = Files.getFileAttributeView(path,
FileOwnerAttributeView.class);
UserPrincipal userPrincipal = view.getOwner();
System.out.println(userPrincipal.getName());
}
}
You can achieve this in JDK 7 using new IO API (Java NIO)
There are getOwner()/setOwner() methods available to manage ownership of files, and to manage groups you can use PosixFileAttributeView.setGroup()
The following code snippet shows how to set the file owner by using the setOwner method:
Path file = ...;
UserPrincipal owner = file.GetFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByName("sally");
Files.setOwner(file, owner);
There is no special-purpose method in the Files class for setting a group owner. However, a safe way to do so directly is through the POSIX file attribute view, as follows:
Path file = ...;
GroupPrincipal group =
file.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByGroupName("green");
Files.getFileAttributeView(file, PosixFileAttributeView.class)
.setGroup(group);

How to get this property value in my java code?

I'm learning Java and sometimes I have some problem to retrieve the information I need from objects...
When I debug my code I can see in targetFile, a path property but I don't know how to get it in my code.
This is a screenshot:
(source: toile-libre.org)
This is my complete code:
package com.example.helloworld;
import com.github.axet.wget.WGet;
import com.github.axet.wget.info.DownloadInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class HelloWorld {
public static void main(String[] args) throws IOException {
nodejs();
}
public static void nodejs() throws IOException {
// Scrap the download url.
Document doc = Jsoup.connect("http://nodejs.org/download").get();
Element link = doc.select("div.interior:nth-child(2) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(3) > a:nth-child(1)").first();
String url = link.attr("abs:href");
// Print the download url.
System.out.println(url);
// Download file via the scraped url.
URL download = new URL(url);
File target = new File("/home/lan/Desktop/");
WGet w = new WGet(download, target);
w.download();
// Get the targetFile property
// ???
}
}
How can I get this value?
I do not know your code but the field you are interested in may be encapsulated and thus not accessible in your code, but the debugger can see it at runtime :)
Update:
https://github.com/axet/wget/blob/master/src/main/java/com/github/axet/wget/WGet.java
The field is default package, you can only access it from within the package.
This can be frustrating at times, but you should ask yourself why the designers of this class decided to hide this field.

Categories