Java 17 Recipes
-5. Obtaining the Java Execution Path
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- How It Works
- 8-6. Copying a File Problem You need to copy a file from one folder to another. Solution
8-5. Obtaining the Java Execution Path
Problem You want to get the path where the Java program is running. Solution Invoke the System class’s getProperty method. The following is an example. String path = System.getProperty("user.dir"); The main class is: public class Ch_8_5_path { public static void main(String[] args) { String path = System.getProperty("user.dir"); System.out.println(path); } } And the output in a windows OS is: C:\eclipse-workspace\java17Recipes How It Works When a Java program starts, the JRE updates the user.dir system property to record where the JRE was invoked. The solution example passes the "user.dir" property name to the getProperty method, which returns the value. ChApTer 8 InpuT And OuTpuT 312 8-6. Copying a File Problem You need to copy a file from one folder to another. Solution From the default java.nio.file .FileSystem abstract class, you create the “to” and “from” paths where the files/folders exist and then use the Files.copy static method to copy files between the created paths. public static void main (String[] args) { Ch_8_6_CopyFileExample exampleCh86 = new Ch_8_6_CopyFileExample(); exampleCh86.copyFile(); } private void copyFile() { FileSystem fileSystem = FileSystems.getDefault(); Path sourcePath = fileSystem.getPath("file.log"); Path targetPath = fileSystem.getPath("file2.log"); System.out.println("Copy from "+sourcePath.toAbsolutePath(). toString()+ " to "+targetPath.toAbsolutePath().toString()); try { Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_ EXISTING); } catch (IOException e) { e.printStackTrace(); } } How It Works In the new NIO.2 libraries, Java works with an abstraction level that allows for more direct manipulation of file attributes belonging to the underlying operating system. FileSystems. getDefaults() gets the usable abstract system on which you can do file operations. ChApTer 8 InpuT And OuTpuT 313 After getting the default FileSystem object, you can query for file objects. In the NIO.2 file, folders and links are all called paths. Once you get a path, you can perform operations with it. In this example, Files.copy is called with the source and destination paths. The last parameter refers to the different copy options. The different copy options are file system dependent, so make sure that the one you choose is compatible with the operating system you intend to run the application in. Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling