分享

Java文件操作

 duduwolf 2005-10-16

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();
  }
 }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多