Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet159/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   155   156   157   158   159   160   161   162   ...   245
Bog'liq
Java 17 Recipes

8-7. Moving a File
 Problem
You need to move a file from one file system location to another.
 Solution
You use the default 
java.nio.file
.FileSystem abstract class to create the “to” and “from” 
paths, and invoke the Files.move() static method.
public static void main (String[] args) {
Ch_8_7_MoveFileExample exampleCh87 = new Ch_8_7_MoveFileExample();
exampleCh87.moveFile();
}
private void moveFile() {
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.move(sourcePath, targetPath);
} catch (IOException e) {
e.printStackTrace();
}
}
ChApTer 8 InpuT And OuTpuT


314
 How It Works
In the same manner as copying a file, create the source and destination path. Then, 
Files.move moves the file from one location to another for you. Other methods provided 
by the Files object are the following.
• Delete (path): Deletes a file (or a folder, if it’s empty).
• Exists (path): Checks whether a file/folder exists.
• isDirectory (path): Checks whether the path created points to a 
directory.
• isExecutable (path): Checks whether the file is an executable.
• isHidden (path): Checks whether the file is visible or hidden in the 
operating system.
You can work with the Delete and Exist methods with the following main method.
public static void main (String[] args) {
FileSystem fileSystem = FileSystems.getDefault();
Path deletePath = fileSystem.getPath("deletePath");
System.out.println("Path to delete:"+deletePath.
toAbsolutePath().toString());
System.out.println("Exist Path to delete? "+Files.
exists(deletePath));
try {
Files.delete(deletePath);
} catch (IOException e) {
e.printStackTrace();
}
}
The output is:
Path to delete:C:\eclipse-workspace\java17Recipes\deletePath
Exist Path to delete? true
ChApTer 8 InpuT And OuTpuT


315

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   155   156   157   158   159   160   161   162   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling