Fayl manzilida ajratuvchi belgisi Windows va Unixda bir-birdan farq qiladi. Windowsda bu belgi “\” kabi bo’lsa, Unixda esa aksi “/” kabidir. Javaning windowsdagi versiyasidan foydalanayotganda “\” belgi \\ belgi bilan yozilishi kerakligini unutmaslik kerak.
public static ArrayList getAllFileInDirectory(String rootPath) { ArrayList list = new ArrayList<>(); File file = new File(rootPath); String s[] = file.list(); if (s != null) { for (String value : s) { File file1 = new File(rootPath + "\\" + value); if (file1.isDirectory()) { list.addAll(getAllFileInDirectory(rootPath + "\\" + value)); } if (file1.isFile()) { list.add(file.getPath() + "\\" + value); } } } return list; }
I/O - All files
ArrayList list = getAllFileInDirectory("D:\\"); list.forEach(System.out::println);
Berilgan katalogdagi barcha fayllarni ko’rish. Masalan D:\ diskdagi barcha fayllarni ko’rish uchun:
I/O - FilenameFilter
boolean accept(File directory, String filename) public class OnlyExt implements FilenameFilter { String ext; public OnlyExt(String ext) { this.ext = "." + ext; } public boolean accept(File dir, String name) { return name.endsWith(ext); } }
I/O - FilenameFilter
String dirname = "D:\\"; File f1 = new File(dirname); FilenameFilter only = new OnlyExt("cpp"); String s[] = f1.list(only); for (String value : s) { System.out.println(value); }
I/O - Stream
Ma’lumotlarni oqimli ketma-ketlikda tas’virlash mumkin. Ikki xil oqim mavjud:
InPutStream − bundan foydalaniladi ma’lumotlarni manbaadan o’qish uchun.
OutPutStream − bunday foydalaniladi ma’lumotlarni yozish uchun.
I/O - Byte Streams
FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } }
I/O - Character Streams
FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } }