Files etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Files etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

6 Ekim 2023 Cuma

Files.lines metodu - NIO

Giriş
Bir stream döndürür. Bu stream'in kapatılması gerekir.  Dolayısıyla ben Files.readString() veya Files.readAllLines() metodunu tercih ediyorum. Eğer bu metodu kullanmak gerekiyorsa mutlaka try()/catch() içinde olmalı.

Örnek
Şöyle yaparız.
String file = ...;
try(Stream<String> stream = Files.lines(Paths.get(file))) {
  stream....;
}
Örnek
Şöyle yaparız.
List<String> list = null;
URI uri = ...;

try (Stream<String> lines = Files.lines(Paths.get(uri))) {
  list = lines.collect(Collectors.toList());
} catch (IOException e) {
  ...
}

3 Ekim 2023 Salı

Files.readString metodu - NIO

Giriş
İki tane overload edilmiş hali var
public static String readString(Path path) throws IOException 
public static String readString(Path path, Charset cs) throws IOException

Birinci overload UTF-8 olarak okur

Files.walk metodu - NIO

Giriş
Bir stream döndürür. Bu stream'in kapatılması gerekir. Files.list metodu ile de Stream'in kapatılması gerekir


Örnek
Şöyle yaparız.
Path path = //...
try (Stream<Path> walk = Files.walk(path)) {
  boolean allMatch = walk
    .filter(Files::isRegularFile)
    .allMatch(p -> );
}
Files.walk yerine eski File.listFiles çok daha kolay olabilir. Şöyle yaparız.
File file = new File("...);
File[] filesInFolder = file.listFiles();
Örnek
Şöyle yaparız.
try (Stream<Path> paths = Files.walk(Paths.get("myDirectory"))) {
    paths.filter(Files::isRegularFile)
         .forEach(System.out::println);
}

8 Şubat 2023 Çarşamba

Files.list metodu - NIO - Belirtilen Dizindeki Elemanları Verir

Giriş
Bir stream döndürür. Bu stream'in kapatılması gerekir. Files.walk metodu ile de Stream'in kapatılması gerekir 

Örnek
Şöyle yaparız
public Set<String> listFilesUsingFilesList(String dir) throws IOException {
  try (Stream<Path> stream = Files.list(Paths.get(dir))) {
    return stream
      .filter(file -> !Files.isDirectory(file))
      .map(Path::getFileName)
      .map(Path::toString)
      .collect(Collectors.toSet());
  }
}
Örnek
Şöyle yaparız
public boolean fileDoesNotExist(String fileName) throws IOException {
  Path tempDirectory = Paths.get(System.getProperty("java.io.tmpdir"));
  try (Stream<Path> stream = Files.list(tempDirectory)) {
    return stream.noneMatch(fullPath -> {
      Path fileName = fullPath.getFileName()
      return fileName.startsWith(fileName);
}); } }


7 Şubat 2023 Salı

Files.copy metodu - NIO

copy metodu  - Path + Path + options
Örnek
Şöyle yaparız.
Path sourceFile = ...;
Path targetFile = ...;
// copy..
Files.copy(sourceFile,targetFile, StandardCopyOption.REPLACE_EXISTING);
copy metodu - InputStream + Path + options
Örnek
Şöyle yaparız
InputStrean src = ...;
Path dest = ...;
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
Örnek
Şöyle yaparız.
URL url = ...;
Path targetPath = ...;
Files.copy(url.openStream(), targetPath,StandardCopyOption.REPLACE_EXISTING);

26 Ocak 2023 Perşembe

Files.newInputStream metodu - NIO

Giriş
Eğer Path olarak bir dizin verirse java.nio.file.AccessDeniedException fırlatır. Kalıtım şöyle
Exception
  IOException
    FileSystemException
      AccessDeniedException

Ö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"
}

18 Ocak 2023 Çarşamba

Files Sınıfı İle Temporary Dosya Yaratma - NIO

Giriş
Dosya yaratma için createTempFile() kullanılır. Bu metodun da 2 tane overload edilmiş hali var

İmzaları şöyle
// Belirtilen dizinde temp dosya yaratır
Path createTempFile(Path dir,
                    String prefix,
                    String suffix,

                    FileAttribute<?>... attrs) throws IOException

// Sistem dizininde temp dosya yaratır
Path createTempFile(String prefix,
                    String suffix,
                    FileAttribute<?>... attrs) throws IOException
1. Her iki metod da Path nesnesi döner. Path nesnesi toFile() metodu ile File nesnesine çevrilebilir.

2. Eğer prefix null verilirse dosya ismi rastgele üretilen sayı ile başlar. 
Örneğin /tmp/4024018108441457842.log

3. Eğer suffix null verilirse varsayılan suffix ".tmp" olur. 
Örneğin /tmp/11485851858110293663.tmp

4. Eğer suffix "" yani boş string verilirse dosya ismine dahil edilmez. 
Örneğin tmp/hello7797826277559942279

5. Hem prefix hem de suffix null ise dosya ismi sadece rastgele üretilen sayı olur. 
Örneğin /tmp/14576820704460531496.tmp

1. Sistem Dizininde
Dosya ismi için prefix ve suffix alır.
Örnek
Şöyle yaparız. İşletim sisteminde ayarlı temporary dizin kullanılır ve rastgele bir isim üretilir.
// C:\Users\Anghel\AppData\Local\Temp\16106384687161465188.tmp
Path tmpNoPrefixSuffix = Files.createTempFile(null, null);
Örnek
Şöyle yaparız.İşletim sisteminde ayarlı temporary dizin kullanılır belirtilen prefix ile başlayıp belirtilen suffix ile biten bir isim üretilir.
// C:\Users\Anghel\AppData\Local\Temp\log_402507375350226.txt
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
Path tmpCustomPrefixAndSuffix = Files.createTempFile(customFilePrefix, customFileSuffix);
Örnek
Şöyle yaparız. İşletim sisteminde ayarlı temporary dizin kullanılır belirtilen prefix ile başlayıp belirtilen suffix ile biten bir isim üretilir.
File file = Files.createTempFile("lambda", "ser").toFile();
Örnek - Permission
Tüm sistemlerde çalışır. Şöyle yaparız
// Create a new temporary file
Path jarPath = Files.createTempFile("myfile", ".jar"); 

// Make it accessible only by the owner
File jarFile = jarPath.toFile();
boolean success = jarFile.setReadable(true, true);
if (!success) {
  ...
}
success = jarFile.setWritable(true, true);
if (!success) {
  ...
}
success = jarFile.setExecutable(true, true);
if (!success) {
  ...
}
2. Belirtilen Dizinde

Belirtilen dizinde bir geçici dosya yaratır. Bu metod File.createTempFile() metoduna tercih edilmeli. Açıklaması şöyle
The temporary files created using File.createTempFile have very unrestricted file permissions so that (at least on my system) anybody can read it. If you are writing security-sensitive application (e.g. for encrypting data), it may be a serious issue.
Dosya ismi için prefix ve suffix alır.
Örnek
Şöyle yaparız. Belirtilen dizin kullanılır belirtilen prefix ile başlayıp belirtilen suffix ile biten bir isim üretilir.
// D:\tmp\log_13299365648984256372.txt
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customFilePrefix = "log_";
String customFileSuffix = ".txt";
Path tmpCustomLocationPrefixSuffix
  = Files.createTempFile(customBaseDir, customFilePrefix, customFileSuffix);
Örnek - Permission
Sadece Linux sistemlerde çalışır. Şöyle yaparız
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

try {

 // Create a temporary file in a specified folder + file permission
 Path path = Paths.get("/home/mkyong/test/");

 // 777
 Set<PosixFilePermission> fp =
   PosixFilePermissions.fromString("rwxrwxrwx");

  Files.createTempFile(path, null, ".log",
                      PosixFilePermissions.asFileAttribute(fp));

  } catch (IOException e) {
   ...
}



30 Ocak 2020 Perşembe

Files Sınıfı İle Temporary Dizin Yaratma - NIO

Giriş
Dizin yaratma için createTempDirectory() kullanılır. Path nesnesi döner. Bu metodun 2 tane overload edilmiş hali var.
- Birinci halinde işletim sisteminde ayarlı temporary dizin kullanılır. İstersek dosyaya prefix verebiliriz.
- İkinci halinde kendi belirttiğimiz bir dizinde temporary dizin yaratılır

createTempDirectory metodu - String prefix
Yaratılan dizin için File.deleteOnExit() yapılırsa JVM'den çıkarken dizin silinir.
Örnek
Şöyle yaparız. İşletim sisteminde ayarlı temporary dizin kullanılır.
// C:\Users\Anghel\AppData\Local\Temp\8083202661590940905
Path tmpNoPrefix = Files.createTempDirectory(null);
Örnek
Şöyle yaparız. İşletim sisteminde ayarlı temporary dizin kullanılır.
// C:\Users\Anghel\AppData\Local\Temp\logs_5825861687219258744
String customDirPrefix = "logs_";
Path tmpCustomPrefix = Files.createTempDirectory(customDirPrefix);
createTempDirectory metodu - Path + String prefix + attributes
İmzası şöyle.
public static Path createTempDirectory(Path dir,
                       String prefix,
                       FileAttribute<?>... attrs)
                                throws IOException
Açıklaması şöyle.
Creates a new directory in the specified directory, using the given prefix to generate its name. The resulting Path is associated with the same FileSystem as the given directory.
The details as to how the name of the directory is constructed is implementation dependent and therefore not specified. Where possible the prefix is used to construct candidate names.
Örnek
Şöyle yaparız. Belirttiğimiz dizin kullanılır.
// D:\tmp\logs_10153083118282372419
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
String customDirPrefix = "logs_";
Path tmpLocation = Files.createTempDirectory(customBaseDir, customDirPrefix);


2 Ekim 2019 Çarşamba

Files Sınıfı - NIO

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

createDirectory metodu
Files İle Dizin Yaratma yazısına taşıdım.

createDirectories metodu
Files İle Dizin Yaratma yazısına taşıdım.

createFile metodu
Örnek ver

createLink metodu
Örnek ver

createSymbolicLink metodu
Örnek
Şöyle yaparız
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.");
}

createTempDirectory metodu
Files Sınıfı İle Temporary Dosya Dizin Yaratma yazısına taşıdım.

createTempFile metodu
Files Sınıfı İle Temporary Dosya Yaratma yazısına taşıdım.

delete metodu
Şöyle yaparız
Path path = Paths.get("myfile.txt");
Files.delete(path);
deleteIfExists metodu
Şöyle yaparız
Path path = Paths.get("myfile.txt");
Files.deleteIfExists(path);
getAttribute metodu
Şöyle yaparız
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
Şöyle yaparız
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 metodu
Files.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 metodu
Eğ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
Files.readString metodu yazısına taşıdım

setLastModifiedTime metodu
Örnek
Şöyle yaparız
FileTime 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
Şöyle yaparız
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
Şöyle yaparız
Path filePath = Files.writeString(
  Files.createTempFile(Path.of("../java11"), "techisbeautiful", ".txt"), 
  "Tech is beautiful"
);