Java文件操作(转载)

来源:互联网 发布:javascript 解析json 编辑:程序博客网 时间:2024/05/24 03:53

Java文件操作(转载)

Java文件操作(转载)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
  *
  * 先判断文件是否存在,然后判断文件是否为空。
  * 如果存在且不为空,则输出文件内容在控制台。
  *
  * @author rmouse_2005   
  * @data 2005-10-14   
  * @version 1.0
  */  
public class Test {
/**
  *
  * Test类主函数
  *
  * @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();
  }
}
}
原创粉丝点击