Java get my documents

Java get my documents

Path testFile = Paths.get(«C:\\Users\\jleom\\Desktop\\java\\javarush task\\test.txt»); Path testFile2 = Paths.get(«C:\\Users\\jleom\\Desktop»); System.out.println(testFile.relativize(testFile2));

Класс Path и класс Paths предназначены для работы с файловой системой в Java, однако они предоставляют разные функции и методы. Path — это интерфейс, который определяет методы для работы с путями к файлам и каталогам в файловой системе. Он предоставляет ряд методов для работы с путями, таких как resolve(), relativize(), getParent(), getFileName(), toAbsolutePath() и другие. Paths — это утилитный класс, который предоставляет статические методы для создания экземпляров класса Path. Он не имеет методов для работы с путями напрямую, но предоставляет методы для создания экземпляров Path из строковых значений или URI. Еще методы по классу Paths: getFileSystem(): возвращает объект FileSystem, представляющий файловую систему, которой принадлежит данный путь. getDefault(): возвращает объект FileSystem, представляющий файловую систему по умолчанию. getTempDirectory(): возвращает объект типа Path, представляющий временный каталог. getHomeDirectory(): возвращает объект типа Path, представляющий домашний каталог пользователя. exists(Path path, LinkOption. options): проверяет, существует ли файл или каталог, представленный указанным путем. Класс Paths удобен для работы с файловой системой, так как он предоставляет простой и удобный API для работы с путями.

Надо добавить в статью, Paths.get был в 8 Java. Потом появился Path.of. Если у вас не работает Path.of (версия Java не позволяет), только тогда нужен Paths.get

Источник

Code Example: Retrieving File Path in Java

The path of an entity can either be an absolute location address from the root or a relative location address that is based on another path.

How to get the path of running java program [duplicate]

System.getProperty("java.class.path") 

Please refer to the website http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html.

It’s easy to separate the elements of it as well.

String classpath = System.getProperty("java.class.path"); String[] classpathEntries = classpath.split(File.pathSeparator); 
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()); 

Substitute the placeholder ‘ MyClass ‘ with the name of your class that includes the primary method.

Alternatively you can also use

System.getProperty("java.class.path") 

The System property mentioned above offers.

The class path is a sequence of directories and JAR archives that contain class files. The elements of this path are separated by a platform-specific character, which is defined in the path.separator property.

Getting the path to your main class is not what you actually want, based on your example. Rather, you need to obtain the current working directory where your program commenced. To achieve this, you can simply use the code snippet below: new File(«.»).getAbsolutePath()

How to get the real path of Java application at runtime?, If you want to get the real path of java web application such as Spring (Servlet), you can get it from Servlet Context object that comes with your HttpServletRequest.

Читайте также:  Рандомные целые числа питон

Get file full path in java

The following statement from the Javadoc documentation could potentially provide assistance:

A pathname can be either absolute or relative, whether in abstract or string form. An absolute pathname is self-contained and requires no additional information to locate the file it represents. In contrast, a relative pathname must be interpreted with reference to another pathname’s information. The classes in the java.io package, by default, resolve relative pathnames against the current user directory directory. This directory is named by the system property user.dir and is usually the directory where the Java virtual machine was invoked.

My understanding is that when you instantiate your File instance using new File(«filename») , and if filename is a relative path, it won’t be transformed into an absolute path even when file.getAbsolutePath() is invoked.

As you have shared the code, I can suggest a few enhancements to it now.

  • One way to locate the necessary files is by implementing a FilenameFilter.
  • It should be noted that list and listFiles both result in null for non-directory items. Therefore, an additional verification is necessary.
  • In the inner loop, it is possible to reuse listFiles() instead of creating new File objects with manually appended \ paths. However, it should be noted that appending \ manually to the path is not recommended as it is not portable. The recommended approach is to use File.separator .
private static void doSomethingToDirectory(File factDir) throws IOException < if (factDir.isDirectory()) < for (File file : factDir.listFiles()) < if (file.isDirectory()) < for (File child : file.listFiles(new MyFilter())) < process(child); >> > > > class MyFilter implements FilenameFilter < public boolean accept(File dir, String name) < return name.equals(TEMP_COMPARE_FILE); >> 

Please be aware that the code emulates the actions of your original code to the best of my comprehension. Specifically, it locates files with the correct name exclusively in the immediate subdirectories of factDir , without traversing further.

There could be a potential solution that may be beneficial to you, but only if the file is located within the program directory.

Initially, the method to obtain the program directory is to:

If file is located within a designated folder such as folder\filename , then the entire pathway will be displayed.

(new File(".").getCanonicalPath() + "\\folder\\filename") 

If file is located within the program directory, the full path will be provided.

(new File(".").getCanonicalPath() + "\\filename") 

i wish this answer help you 🙂

Java File (With Examples), The file object is linked with the specified file path. File file = new File («newFile.txt»); Here, we have used the file object to create the new file with the specified path. If newFile.txt doesn’t exist in the current location, the file is created and this message is shown. The new file is created.

Читайте также:  Matrix shape in python

Getting My Documents path in Java

Discovering JFileChooser is a breeze with the assistance of our tool.

new JFileChooser().getFileSystemView().getDefaultDirectory().toString(); 

I hope this helps someone

As per @xchiltonx’s highly upvoted answer that utilizes JFileChooser , I would like to mention that in terms of performance, JFileChooser is quicker compared to JFileChooser .

FileSystemView.getFileSystemView().getDefaultDirectory().getPath() 

The required time for executing JFileChooser on my computer was 300ms, whereas calling FileSystemView directly took less than 100ms.

It should be noted that this question may be a duplicate of another question regarding the location of the «My Documents» folder in Java.

A registry query can retrieve it without requiring JNA or admin rights.

Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal"); 

It is apparent that this method is only applicable to Windows and its compatibility with Windows XP is uncertain.

Incorporate this into a functional code sequence.

String myDocuments = null; try < Process p = Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal"); p.waitFor(); InputStream in = p.getInputStream(); byte[] b = new byte[in.available()]; in.read(b); in.close(); myDocuments = new String(b); myDocuments = myDocuments.split("\\s\\s+")[4]; >catch(Throwable t) < t.printStackTrace(); >System.out.println(myDocuments); 

Keep in mind that the process will be locked until «reg query» is finished, and this could potentially create issues depending on the task at hand.

How to get the relative path of the file to a folder using, Perhaps there’s a library somewhere out there that does it (I can’t think of any offhand, and Apache Commons IO doesn’t appear to have it). You could use this or something like it: // returns null if file isn’t relative to folder public static String getRelativePath (File file, File folder) < String filePath = …

Path getFileSystem() method in Java with Examples

In Java 7, the Path interface was introduced to Java NIO. This interface is located within the java.nio.file package and its fully qualified name is java.nio.file.Path. A Java Path instance is used to represent a file system path, which can refer to either a file or directory. Paths can be categorized as either absolute or relative. Absolute paths refer to the entity location address from the root, while relative paths refer to a location address that is relative to another path.

The method «getFileSystem()» in the Java class «java.nio.file.Path» retrieves the file system that generated the corresponding Path instance.

The method being referred to doesn’t require any input parameters.

The Path object’s creator file system is returned by this method.

The following code snippets demonstrate the usage of the getFileSystem() method: Snippet 1:

The following codes are listed below and numbered consecutively: 1. msdt_code1 2. msdt_code2 3. msdt_code3 4. msdt_code4 msdt_code5 5. msdt_code6 msdt_code7 6. msdt_code8 msdt_code9 7. msdt_code10 msdt_code11 8. msdt_code12 9. msdt_code13 msdt_code14 msdt_code15 10. msdt_code16 msdt_code17 msdt_code18 msdt_code19 msdt_code20 11. msdt_code21 msdt_code22 msdt_code23 12. msdt_code24 msdt_code25 13. msdt_code26 14. msdt_code27 msdt_code28 15. msdt_code29 msdt_code30 16. msdt_code31 msdt_code32 msdt_code33 msdt_code34 17. msdt_code35 18. msdt_code36 msdt_code37 19. msdt_code38 msdt_code39 20. msdt_code40 msdt_code41 21. msdt_code42 22. msdt_code43 msdt_code44 23. msdt_code45 msdt_code46 msdt_code47 24. msdt_code48 msdt_code49 25. msdt_code50 msdt_code51 26. msdt_code52.
Separator used for FileSystem: /
The text consists of a list of fifty codes labeled as MSDT_code1 through MSDT_code50. The codes range from MSDT_code1 to MSDT_code50, with no repetition in between. The codes are not grouped together in any particular way, but are listed in numerical order from MSDT_code1 to MSDT_code50.
FileSystem is ReadOnly: false

The documentation for Java SE version 10 contains information about the «Path» class, including a method called «getFileSystem().

Читайте также:  Android java access database

Java NIO — Path, In order to get the instance of Path we can use static method of java.nio.file.Paths class get () .This method converts a path string, or a sequence of strings that when joined form a path string, to a Path instance.This method also throws runtime InvalidPathException if the arguments passed contains illegal characters.

Источник

Getting My Documents path in Java

You can get it using a registry query, no need for JNA or admin rights for that.

Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal"); 

Obviously this will fail on anything other than Windows, and I am not certain whether this works for Windows XP.

EDIT: Put this in a working sequence of code:

String myDocuments = null; try < Process p = Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v personal"); p.waitFor(); InputStream in = p.getInputStream(); byte[] b = new byte[in.available()]; in.read(b); in.close(); myDocuments = new String(b); myDocuments = myDocuments.split("\\s\\s+")[4]; >catch(Throwable t) < t.printStackTrace(); >System.out.println(myDocuments); 

Note this will lock the process until «reg query» is done, which might cause trouble dependeing on what you are doing.

Note in 2020: The ShellFolder class seems to be missing on Linux (tested with openjdk8), so IvanRF’s answer is likely better.

Original answer:

The best way I’ve found is to use AWTs:

ShellFolder.get("fileChooserDefaultFolder"); 

I have redirected my Documents folder to the D: drive, and it successfully fetches this directory. It also does so in about 40 ms (on my machine). Using FileSystemView takes about 48 ms, and new JFileChooser() about 250 ms.

All three of these methods actually use ShellFolder under the hood, and the difference with FileSystemView is negligible, but calling it directly avoids the overhead of the other two.

Note: You can also cast this directly to File instead of implicitly getting the toString() method of it, which can help you further:

File documents = (File) ShellFolder.get("fileChooserDefaultFolder"); 

Since the most upvoted answer from @xchiltonx uses JFileChooser I would like to add that, regarding performance, this is faster than using JFileChooser :

FileSystemView.getFileSystemView().getDefaultDirectory().getPath() 

In my PC, JFileChooser aproach needed 300ms, and calling FileSystemView directly needed less than 100ms.

Note: The question is a possible duplicate of How to find “My Documents” folder in Java

Источник

Оцените статью