I have a directory: <dir>\Report\<env>\Log_XXX\Logs
where XXX is randomly created at run time, so I have to create a file inside Logs folder.
Following is what I tried to generate the Logs folder:
new File(System.getProperty("user.dir") + "/Report/" + System.getProperty("env") + "/" + Pattern.compile("^Log_") + "/Logs").mkdirs();
Based on your comments, it appears you are trying to locate the one and only subdirectory whose base name starts with Log_. You can accomplish this with Files.list:
Path logParent = Paths.get(
System.getProperty("user.dir"),
"Report",
System.getProperty("env"));
Path logDir;
try (Stream<Path> listing = Files.list(logParent)) {
Optional<Path> match = listing.filter(p -> Files.isDirectory(p) &&
p.getFilename().toString().startsWith("Log_")).findFirst();
logDir = match.orElseThrow(() -> new RuntimeException(
"No log directory found in " + logParent));
}
Related
This question already has answers here:
Setting file creation timestamp in Java
(4 answers)
Closed 3 years ago.
I have a piece of Java code that will create a new file and fill it with existing data elsewhere. When right clicking on the file and looking at its properties. There will be this property "Created" and "Modified" which are set to the date when the file was created by the code.
I would like to retain the Created/Modified date that the old file had. Is it possible?
ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
if (reader == null)
{
// no data for this node
return false;
}
File output = new File(outputFileName);
reader.getContent(output);
See https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/BasicFileAttributeView.html and/or https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/attribute/BasicFileAttributeView.html
"The setAttribute method may be used to update the file's last modified time, last access time or create time attributes as if by invoking the setTimes method."
File metadata can be fetched as File attributes. Sample example is as below.
File attributes is part of java.nio.file.attribute package.
File file = new File(outputFileName);
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
System.out.println("isDirectory: " + attr.isDirectory());
System.out.println("isOther: " + attr.isOther());
System.out.println("isRegularFile: " + attr.isRegularFile());
System.out.println("isSymbolicLink: " + attr.isSymbolicLink());
System.out.println("size: " + attr.size());
This should give you required details.
I've been trying to get the absolute path of the class I am working on.
I have tried doing this:
Class currentClass = new Object() {
}.getClass().getEnclosingClass();
System.out.println(currentClass);
System.out.println(" PATH IS: " + currentClass.getProtectionDomain().getCodeSource().getLocation());
System.out.println("Present Project Directory : " + System.getProperty("user.dir"));
BUT I am getting this kind of output:
PATH IS: file:/C:/Users/jean/eclipse-workspace/AutoCompile/bin/
Present Project Directory : C:\Users\jean\eclipse-workspace\MyProject
I want to get a result like this:
C:\Users\jean\eclipse-workspace\MyProject\src\com\school\demo\Locator.java
I run my class in the command line, it's ok, but When I package my project as the service of Windows, it's failed. Anyone get the reason?
My service run as the System user, the tempFolder was created as System user.
There is my code, and I didn't get any exception and error.
(!tempFolder.exists()){
if(tempFolder.mkdirs()){
String operatingSystemName = System.getProperty("os.name");
if (operatingSystemName != null
&& operatingSystemName.startsWith(WINDOWS_FAMILY)) {
String string = " attrib " + tempFolder.getAbsolutePath()+ " +h";
try {
Runtime.getRuntime().exec(string);
} catch (Exception e) {
e.printStackTrace();
}
}
}else {
throw new Exception("Can't create temp folder - " + tempFolder.toString());
}
Add parameter +s
String string = " attrib " + tempFolder.getAbsolutePath()+ " +s +h";
+s : Used to set the file attribute as a system file.
Parameters of attrib command
+r : Used to set the file attribute as read-only.
-r : Used to clear the read-only file attribute.
+a : Used to set the file attribute as archive.
-a : Used to clear the archive file attribute.
+s : Used to set the file attribute as a system file.
-s : Used to clear the system file attribute.
+h : Used to make the file attribute as hidden not visible to the user.
-h : Used to clear the hidden file attribute.
If I try to use a path that contains spaces in Linux I get FileNotFoundException, obviously. But if I try to add double/single quotes in the path as workaround, I get the same exception.
I was trying to check the reason and I found out that the generated absolute path when using quotes became: the user.home system property + specified path.
For example:
If I use this path:
/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs
This is the absolute path I get when trying to use quotes:
/home/db2inst1/"/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs"
I also tried to replace the spaces with "\ " instead of adding quotes, but it did not work.
I tried a lot of API's and it happens every time, made this code just for testing:
System.out.println("- regular path: ");
System.out.println(new File(path).getPath());
System.out.println(new File(path).getAbsolutePath());
System.out.println("- quoted path: ");
System.out.println(new File(quotedPath).getPath());
System.out.println(new File(quotedPath).getAbsolutePath());
And this is the output:
- regular path:
/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs/testing.log
/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs/testing.log
- absolute path:
"/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs/testing.log"
/home/db2inst1/"/home/db2inst1/Desktop/testing - Development Environmet/64_dev/testing/logs/testing.log"
Does anyone know why this is happening and how to make it work?
From your description it seems that you are calling the File(java.lang.String pathname) constructor.
If so, the String used to represent your path should not use quotes.
Quotes are not considered as special characters in the abstract pathname definition, as described in the java.io.File documentation.
An abstract pathname has two components:
An optional system-dependent prefix string, such as a disk-drive specifier, "/" for the UNIX >root directory, or "\\" for a Microsoft Windows UNC pathname, and
A sequence of zero or more string names.
Since quotes are not special characters, they are considered part of a name.
Example:
public static void main(String[] args) {
File quotes = new File("\"C:\\myFolder\"");
File noQuotes = new File("C:\\myFolder");
System.out.println("Absolute path with quotes:" + quotes.getAbsolutePath());
System.out.println("Absolute path without quotes:" + noQuotes.getAbsolutePath());
System.out.println("Equal: " + quotes.equals(noQuotes));
File empty = new File("");
File emptyQuotes = new File("\"\"");
System.out.println("Empty path with quotes:" + empty.getAbsolutePath());
System.out.println("Empty path without quotes:"
+ emptyQuotes.getAbsolutePath());
System.out.println("Equal: " + empty.equals(emptyQuotes));
}
will produce the following output when run in C:\temp on Windows:
Absolute path with quotes:C:\temp\"C:\myFolder"
Absolute path without quotes:C:\myFolder
Equal: false
Empty path with quotes:C:\temp
Empty path without quotes:C:\temp\""
Equal: false
In windows a file name without blanks and the same quoted should refer to the same file (or folder). For instance if we have a folder called c:\uni2 both command lines
dir c:\uni2
dir "c:\uni2"
should give the same result. But in java
String rename;
boolean ya;
File f1 = new File ("C:/UNI2"); // given that exists and it is a directory
ya = f1.exists(); // true
ya = f1.isFile(); // false
ya = f1.isDirectory(); // true
rename = f1.getAbsolutePath(); // "C:\\UNI2"
f1 = new File ("\"C:/UNI2\""); // in windows this should be the same directory!!
ya = f1.exists(); // false
ya = f1.isFile(); // false
ya = f1.isDirectory(); // false
rename = f1.getAbsolutePath(); // "C:\tmp\"C:\UNI2""
which is not the expected behavior (even if it is documented).
I try to access a network folder / UNC path from Java on Mac OSX. On Windows, the following test program works fine (at least one of the tested paths):
public class PathTest {
public static void main(String[] args) {
for (String path : Arrays.asList(
"\\\\myserver\\transfer", "//myserver/transfer", "file://myserver/transfer", "smb://myserver/transfer")) {
File f = new File(path);
System.out.println(path + ": " + f.getAbsolutePath() + ", " + f.exists());
Path p = Paths.get(path);
System.out.println(path + ": " + p.toAbsolutePath() + ", " + Files.exists(p));
}
}
}
on Mac OS it fails to reach the folders:
\\myserver\transfer: /Users/tim/IdeaProjects/PathTest/\\myserver\transfer, false
//myserver/transfer: /myserver/transfer, false
file://myserver/transfer: /Users/tim/IdeaProjects/PathTest/file://myserver/transfer, false
smb://myserver/transfer: /Users/tim/IdeaProjects/PathTest/smb://myserver/transfer, false
When I use Finder, I can access the Folder (using the Guest user), by using "smb://myserver/transfer". What's wrong?
EDIT added NIO.2 test
Either mount the partition and access it as any local directory or use a specialized library such as JCIFS or Apache Commons VFS.