|
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException;
/** * * 先判斷文件是否存在,然后判斷文件是否為空。 * 如果存在且不為空,則輸出文件內(nèi)容在控制臺。 * * @author rmouse_2005 * @data 2005-10-14 * @version 1.0 */
public class Test {
/** * * Test類主函數(shù) * * @param args * @throws IO異常 */ public static void main(String[] args) throws IOException { String path = "h:\\eclipse\\test\\a.txt"; Test t = new Test(); if (t.isExist(path)) { if (t.isEmpty(path)) { System.out.println("success!"); System.out.println(); t.getValue(path); } else {
System.out.println("false!"); } } else { System.out.println("false!"); } }
/** * * 判斷文件是否存在 * * @param file 文件名 * @return 文件是否存在 * true - 文件存在 * false - 文件不存在 */ boolean isExist(String file) { File f = new File(file); if (f.exists()) { System.out.println("File is Exist!"); return true; } else { System.out.println("File isn‘t Exist!"); return false; } }
/** * * 判斷文件是否為空 * * @param file 文件名 * @return 文件是否為空 * true - 文件為空 * false - 文件不為空 * @throws IO異常 */ boolean isEmpty(String file) throws IOException { FileReader fr = new FileReader(file); if (fr.read() == -1) { System.out.println("File is Empty!"); return false; } else { System.out.println("File isn‘t Empty!"); return true; } }
/** * * 讀取文件 * * @param file 文件名 * @throws IO異常 */ void getValue(String file) throws IOException { FileReader fr; fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = ""; line = br.readLine(); while (line != null) { String lineNew = ""; lineNew = line; System.out.println(lineNew); line = br.readLine(); } } }
|