Giriş
Şu satırı dahil
ederiz.
import java.nio.file.Files;
Bu sınıf
Objects,
Arrays gibi tamamen static metodlardan oluşan yardımcı bir sınıftır. Açıklaması
şöyle.
This class consists exclusively of static methods that operate on files, directories, or other types of files.
copy metodu Path + Path
Açıklaması
şöyle
By default, the copy fails if the target file already exists
Şöyle
yaparız. File nesneleri yine Path tipine çevriliyor.
void copyFile(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
copy metodu
Files.copy metodu yazısına taşıdım
createLink metodu
Örnek ver
createSymbolicLink metodu
Örnek
Path newLink = Paths.get("myLink");
Path existingFile = Paths.get("existingFile.txt");
// Creating a symbolic link
Files.createSymbolicLink(newLink, existingFile);
// Checking if a path is a symbolic link
if (Files.isSymbolicLink(newLink)) {
System.out.println(newLink + " is a symbolic link.");
}
Path path = Paths.get("myfile.txt");
Files.delete(path);
deleteIfExists metodu
Path path = Paths.get("myfile.txt");
Files.deleteIfExists(path);
getAttribute metodu
Path path = Paths.get("myfile.txt");
FileTime creationTime = Files.getAttribute(path, "creationTime");
System.out.println("Creation Time: " + creationTime);
getLastModifiedTime metodu
Şöyle
yaparız.
FileTime t = Files.getLastModifiedTime(path);
isRegularFile metodu
Örnek
Şöyle
yaparız.
Path filePath = ...;
if (Files.isRegularFile(filePath)) {...}
Örnek
boolean regularFile = Files.isRegularFile(symPath, LinkOption.NOFOLLOW_LINKS);
isWritable metodu
Şöyle
yaparız.
Path path = Paths.get("path/to/my/file");
// is it writable? If no, consider "read only"
boolean canWrite = Files.isWritable(path);
lines metoduFiles.lines metodu yazısına taşıdım
mismatch metodu
Java 12 ile
geliyor. Dosyaların boyu farklıysa küçük olanı döner. Eğer aynıysa ancak byte içeriği farklıysa ilk farklılığın olduğu konumu döner
move metodu - source + target
Açıklaması
şöyle.
Move or rename a file to a target file.
Örnek
Şöyle
yaparız.
Path fileToMovePath = ...;
Path targetPath = ...;
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
move metodu - source + target + options
Örnek - ATOMIC_MOVE
Açıklaması
şöyle.
With an ATOMIC_MOVE you can move a file into a directory and be guaranteed that any process watching the directory accesses a complete file.
Şöyle
yaparız.
Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
Örnek - REPLACE_EXISTING
Şöyle
yaparız.
import static java.nio.file.StandardCopyOption.*;
Files.move(source, target, REPLACE_EXISTING);
newBufferedReader metodu
Şöyle
yaparız.
String CSV_FILE_PATH = "C:Test Data\\names.csv";
try (Reader reader = Files.newBufferedReader(Paths.get(CSV_FILE_PATH))) {
...
}
newBufferedWriter metodu
Şöyle
yaparız.
BufferedWriter w = Files.newWriter(file, Charsets.UTF_8);
newByteChannel metodu
Şöyle
yaparız.
Path path = Paths.get(lfile);
SeekableByteChannel sbc = Files.newByteChannel(path, StandardOpenOption.READ);
newDirectoryStream metodu
Sadece verilen dizini dolaşır. Yani özyinelemeli (recursive) değildir. Şöyle
yaparız.
Path searchPath = Paths.get("c://log");
try (DirectoryStream<Path> fileList = Files.newDirectoryStream(searchPath)) {
for (Path path : fileList) {
System.out.println(path.getFileName());
}
newInputStream metoduEğer Path olarak bir dizin verirse java.nio.file.AccessDeniedException fırlatır. Kaltım şöyle
Exception
FileSystemException
AccessDeniedException
O da zaten IOException fırlatır.
Örnek
Elimizde bir path
olsun
Path path = Paths.get("path/to/my/file");
Şöyle
yaparız.
try (InputStream in = Files.newInputStream(path)) {
// work with "in"
}
newOutputStream metodu
Dosya yoksa yaratılır. Varsa sonuna ekleme yapılır. Şöyle
yaparız.
Path source1 = Paths.get("src1.txt");
Path source2 = Paths.get("src2.txt");
Path destination = Paths.get("dest.txt");
out = Files.newOutputStream(destination, CREATE, APPEND);
Files.copy(source1, destination, StandardCopyOption.REPLACE_EXISTING);
Files.copy(source2, destination);
notExists metodu
Şöyle
yaparız.
Path dirPath = ...;
if(Files.notExists(dirPath)){
Files.createDirectory(dirPath);
}
readAllBytes metodu
İçi
şöyle. Stream'in açılıp kapatıldığı görülebilir.
public static byte[] readAllBytes(Path path) throws IOException {
try (SeekableByteChannel sbc = Files.newByteChannel(path);
InputStream in = Channels.newInputStream(sbc)) {
long size = sbc.size();
if (size > (long)MAX_BUFFER_SIZE)
throw new OutOfMemoryError("Required array size too large");
return read(in, (int)size);
}
}
readAttributes metodu
BasiFileAttributes nesnesi döner.
Örnek
Şöyle
yaparız
Path file = ...;
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
readString metodu
setLastModifiedTime metodu
Örnek
Şöyle
yaparızFileTime newTime = FileTime.fromMillis(System.currentTimeMillis());
Files.setLastModifiedTime(path, newTime);
setPosixFilePermissions metodu
Şu satırı dahil
ederiz.
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
Örnek
Elimizde şu kod
olsun
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-xr-x");
Şöyle
yaparız.
Path path = ...;
Files.setPosixFilePermissions(path, perms);
size metodu
Path path = Paths.get("myfile.txt");
long size = Files.size(path);
System.out.println("Size: " + size + " bytes");
walk metodu
Files.walk metodu yazısına taşıdım
walkFileTree metodu
Java 7 ile geliyor.
Örnek
SimpleFileVisitor sınıfını kullanarak şöyle
yaparız.
Path path = ...;
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){...});
Örnek
FileVisitor arayüzünü kullanarak şöyle
yaparız.
Path path = ...;
Files.walkFileTree(path, new FileVisitor<Path>() {...});
Örnek
Şöyle
yaparız.
Path src = ...;
Files.walkFileTree(src,
EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE,
new SimpleFileVisitor<Path>() {...}
);
write metodu - byte [] + OpenOption
Örnek
Sıfırlayıp tekrar yazmak için (overwrite) şöyle
yaparız.
Files.write(path, content.getBytes());
Açıklaması
şöyle.
The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0
Örnek
Şöyle
yaparız.
try {
Files.write(Paths.get("f.txt"), "text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
...
}
Örnek
Dosya yoksa yaratmak, varsa ekleme yapmak için şöyle
yaparız.
String message = "bla";
Files.write(
Paths.get(".queue"),
message.getBytes(),
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
write metodu - CharSequence + Charset + OpenOption
Şöyle
yaparız.
Path path = ...;
Files.write(path,"text".getBytes(),StandardCharsets.UTF_8);
writeString metodu Örnek
Path filePath = Files.writeString(
Files.createTempFile(Path.of("../java11"), "techisbeautiful", ".txt"),
"Tech is beautiful"
);