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");
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 path)
dö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 metoduFile Sınıfı İle Dizin Yaratma yazısına taşıdım