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

25 Ağustos 2021 Çarşamba

File.mkdir metodu - Kullanmayın

Giriş
Java 7 ile dizin yaratmak için iki tane yöntem var.
1. mkdir
2. mkdirs
Her ikisi de kullanışlı değil, çünkü sonuç olarak sadece Boolean dönüyorlar. Çağrı false dönerse sebebini anlamanın yolu yok. Açıklaması şöyle
So false represents absent parent directory, no permissions, and other IO exceptions. What are other IO exceptions? Here’s the full list:
- The parent directory for the directory may not exist
- The parent directory’s ownership and permissions may be wrong
- The app may not be permitted to write in this file system.
- The device could be read-only
- The device could be corrupted or experiencing hardware errors
- The file system could be so full that a directory cannot be created.

You can’t find the error from false. This code is abandoned nowadays.
Bu metod yerine Files.createDirectory() kullanılmalı. Files Sınıfı İle Dizin Yaratma yazısına bakabilirsiniz

mkdir metodu
İmzası şöyle
public boolean mkdir();
Şöyle yaparız.
File f  = new File("/IdeaProjects/JavaCode/js");
boolean result = = f.mkdir();
mkdirs metodu
Bir çok dizini aynı anda yaratır.  boolean döner. Şöyle yaparız.
File folder = new File(...);
boolean result = folder.mkdirs();
Şöyle yaparız.
File f = new File("/folder/subfolder/subfolder1")
f.mkdirs();
Çıktı olarak şu yapı oluşur.
folder
└── subfolder
    ├── subsubfolder1

21 Şubat 2019 Perşembe

File Sınıfı

Giriş
Bu sınıfı kullanmak için şu satırı dahil ederiz. Java 7'den itibaren bu sınıf yerine Path + Files sınıflarını tercih etmek gerekir.
import java.io.File;
constructor - string
1. string relative path olabilir. Bu kullanımda classpath içindeki bir dosyayı yüklemek mümkün değil. Bu işlem için getResourceAsStream() metodu kullanılmalı. Bu metoda verilen path "/" ile başlamalı

Örneğin "config/a.xml". Eğer tam yolu olmak istersek şöyle yaparız
URI uri = new File("relativePath").toURI();
URL nesnesi istiyorsak şöyle yaparız
URL url = new File("relativePath").toURI().toURL();
Hem URI hem de URL için çıktı olarak şunu alırız
"file:/C:/MyProject/mymodule/config/a.xml"
2. string full path olabilir. Bu durumda zaten her şey belirlir.

Örnek - unix tarzı
Şöyle yaparız.
File f = new File("C:/path/to/where/you/want");
Örnek - escape
Şöyle yaparız
File file = new File("C:\\Users\\Local Admin\\Desktop\\1.txt");
Şu path yanlış
File file = new File("C:\Users\Local Admin\Desktop\1.txt");
Şu hatayı alırız.
Invalid escape sequences.
canX metodları
Şöyle yaparız.
File dir = new File("...");
System.out.println(dir.canRead());
System.out.println(dir.canWrite());
System.out.println(dir.canExecute());
canWrite metodu
Şöyle yaparız.
File f = ...;
if (f.canWrite()) {...}
createNewFile metodu
Boolean bir değer döner. Şöyle yaparız.
File file = new File("hello_world.bat");
boolean result = file.createNewFile();
createTempFile metodu
Geçici bir dosya oluşturur.
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
                 Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
               );
delete metodu
Bir dizinin içindekileri silmek için şöyle yaparız.
boolean deleteDirectory(File[] files) {
  if (files == null) {
    return true;
  }
  for(int i=0; i<files.length; i++) {
    if(files[i].isDirectory()) {
      deleteDirectory(files[i]);
    }
    else {
      files[i].delete();
    }
  }
}
Çağırmak için şöyle yaparız.
String path = 
File[] files = new File(absPath).listFiles();
deleteDirectory (files)
deleteOnExit metodu
Şöyle yaparız.
String name = "delete.me";
new File(name).deleteOnExit();
exists metodu
Belirtilen dizinin var olup olmadığını döner. Şöyle yaparız.
if (!f.exists()) {...}
getAbsolutePath metodu
Tüm yolu döndürür. Şöyle yaparız.
File f = ...;
String s = f.getAbsolutePath();
getCanonicalPath metodu
Tüm yolu (absolute pathdöndürür.

getName metodu
Dosya ismi + uzantıyı verir. Şöyle yaparız.
String path = "C:\\Users\\Ewen\\AppData\\Roaming\\MyProgram\\Test.txt";
File f = new File(path);
System.out.println(f.getName()); // Prints "Test.txt"
getPath metodu
Relative path döndürebilir. Bu durumda getAbsolutePath veya getCanonicalPath ile tüm yol alınır.

getParentFile metodu
Örnek ver.

isDirectory metodu
Şöyle yaparız.
if(f.isDirectory()) {...}
isFile metodu
Şöyle yaparız.
if(f.isFile()){...}
length metodu
Şöyle yaparız.
File file = new File("...");
int length = (int) file.length();
listFiles metodu - recursive değil
Bu metod recursive değil. Recursive dolaşmak için Files.walkFileTree () daha uygun. Java 7 yoksa ve recursive kodlamak gerekirse şöyle yaparız.
File file = new File("D:/");
Stack stack = new Stack<File>();

stack.push(f);

while (!stack.empty())
{    
  file = (File) stack.pop();
  File []list = f.listFiles();
  try{
    for(int i=0;i<list.length && list.length>0;i++){    
      if(list[i].isFile() && (list[i].getName().contains(".pdf")) ||
         list[i].getName().contains(".PDF"))
          System.out.println(list[i].getAbsolutePath()); //Do something
      if(list[i].isDirectory())
        stack.push(list[i]);
    }
  }catch(Exception e){    
  ...
  }
}
Açıklaması şöyle
There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.
Şöyle yaparız.
File[] children = parent.listFiles();
// This will return null if the path does not exist it is not a directory...
Şöyle yaparız.
File[] children = parent.listFiles(new FileFilter() {
  public boolean accept(File file) {
    return file.isDirectory() || file.getName().toLowerCase().endsWith(".dat");
  }
});
// This will return all the files that are directories or whose file name ends
// with ".dat" (*.dat)
Dosya uzantısına göre süzmek için daha kolay bir kod şöyle
File file = new File(source);
File[] files = file.listFiles(new FilenameFilter() {

  @Override
  public boolean accept(File dir, String name) {
    if(name.matches(".*\\.bmp")){
      return true;
    }
    return false;
  }
});
mkdir metodu
File Sınıfı İle Dizin Yaratma yazısına taşıdım

mkdirs metodu
File Sınıfı İle Dizin Yaratma yazısına taşıdım

renameTo metodu
Metodun ismi renameTo olsa da move işlemi için kullanılabilir. Girdi olarak File nesnesi alır, sonuç olarak boolean döner. Şöyle yaparız.
File f = new File("F.txt");
boolean isMoved = f.renameTo (new File("../F.txt"));
separator alanı
Şöyle yaparız.
String path = "abc" + File.separator;
toPath metodu
File ve Path nesneleri birbirlerine dönüştürülebilir. Şöyle yaparız.
File file = new File("some path");
Path filePath = file.toPath();