استفاده از فایلها در جاوا مظفر بگ محمدی دانشگاه ایلام Simple file handling in Java
ذخیره ی اطلاعات در فایلها فایلها بصورت دودویی در کامپیوتر ذخیره می شوند. انواع فایلها: فایل متنی فایل باینری
فایل متنی و باینری فایل متنی فایل باینری هر 8 بیت یک کاراکتر است مثل: ‘0’ = 48, ‘1’ = 49 فایل باینری انواع دیگر فایلها مثلاً ممکن است که داده بصورت اعداد طبیعی 16 بیتی ذخیره شده باشد. 110000 110001 ‘0’ ‘1’ 1100011100102 318610
خواندن متن از یک فایل File BufferedReader FileReader char stream 01000001 01001110 : BufferedReader ‘A’ ‘N’ ‘ ‘ char stream 01000001 01001110 00100000 byte stream string “AN “ FileReader Simple file handling in Java
نوشتن متن در یک فایل File PrintWriter FileWriter Primitives, Strings, Objects “AN “ 01000001 01001110 00100000 byte stream File 01000001 01001110 : PrintWriter ‘ ‘ ‘N’ ‘A’ char stream FileWriter Simple file handling in Java
کلاس IntegerWrapper class IntegerWrapper { private int num; public IntegerWrapper () num = (int) (Math.random() * 100); } public void setNum (int no) num = no; public int getNum () return num;
کلاس SimpleIO import java.io.*; class SimpleIO { public static void main (String [] argv) { IntegerWrapper iw1 = new IntegerWrapper (); IntegerWrapper iw2 = new IntegerWrapper (); String filename = "data.txt"; PrintWriter pw; FileWriter fw; BufferedReader br; FileReader fr;
کلاس SimpleIO (2) try { fw = new FileWriter (filename); pw = new PrintWriter (fw); System.out.println("Written to file: " + iw1.getNum()); pw.println(iw1.getNum()); System.out.println("Written to file: " + iw2.getNum()); pw.println(iw2.getNum()); pw.close(); Simple file handling in Java
کلاس SimpleIO (3) fr = new FileReader(filename); br = new BufferedReader(fr); System.out.println("Read from file: " + br.readLine()); System.out.println("Read from file: " + br.readLine()); } catch (IOException e) { System.out.println(“File IO error: Exception thrown"); e.printStackTrace();