PDA

View Full Version : سوال: در مورد قطعه کد زیر که برای خوندن از فایله سوال داشتم...



daneshjoo91
سه شنبه 20 تیر 1391, 00:09 صبح
در این قطعه کد:

package MyProject

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
* This program reads a text file line by line and print to the console. It uses
* FileOutputStream to read the file.
*
*/
public class FileInput {

public static void main(String[] args) {

File file = new File("C:\\MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;

try {
fis = new FileInputStream(file);

// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {

// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}

// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}









جرا سه تا متغیر fis ، bis و dis تعریف کرده؟ اصلا توضیح این سه خط کد چیه؟

fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

و اینکه چرا دو تا catch داره؟ catch اول چیکار میکنه؟دومی چطور؟
و...چرا با استفاده از هر سه متغیر اومدیم و متد ()closeرو صدا زدیم؟

spiderman200700
سه شنبه 20 تیر 1391, 12:29 عصر
fis و bis و dis به ترتیب آرگومانهای همدیگه هست.
میتونی اینطوری هم بنویسی:
dis = new DataInputStream(new BufferedInputStream( new FileInputStream(file)))

توی catch اول استثنای پیدا نشدن فایل رو کنترل میکنه. و توی دومی استثنای IO رو کنترل میکنه.

در ضمن میتونیم فقط dis رو close کنی.