现在的位置: 首页 > 综合 > 正文

\t\tBufferedWriter操作文件

2014年07月16日 ⁄ 综合 ⁄ 共 2106字 ⁄ 字号 评论关闭
/**
* 创建文件
* @param path 文件名称
*/
public static BufferedWriter createFile(String path){
   BufferedWriter bf = null;
   try {
    File file = new File(path);
    bf = new BufferedWriter(new FileWriter(file));    
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return bf;
  
}

/**向文件中写数据
* @param bf   缓冲写入对象
* @param data   被写入的数据
* @param countLine 写入几行
*/
public static void writeData(BufferedWriter bf ,int data,int countLine){
   //向文件中写数据  
   try {
    for (int i = 0; i < countLine; i++) {    
     bf.write(String.valueOf(data));
     bf.newLine();  
    }   
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
}

/**
* 关闭流
* @param bf
*/
public static void closeWrite(BufferedWriter bf){  
   try {
    if (bf != null){
     bf.close();
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  
}

/**
* 读取文件内容
* @param path 文件路径
*/
public static void readData(String path){  
   try {
    BufferedReader br = new BufferedReader(new FileReader(path));   
    String s = null;
    while((s = br.readLine())!= null){    
     System.out.println(s);
    }
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
}

@Override
public void run() {  
   BufferedReader br;
   try {   
    //构造缓冲输入流
    br = new BufferedReader(new FileReader(path));
    //声明一个为null的变量,用于标记是否读到文件末尾
    String s = null;
    //一行一行循环读取文件    
    while((s = br.readLine())!= null){
     //开始时间
     long start = System.currentTimeMillis();
     //从文件中读取一行,写入数据库   
     createMonitorLog(Integer.valueOf(s));
     //结束时间
     long end = System.currentTimeMillis();    
     //等待一分钟
     doSleep(60*1000+start-end);      
    }       
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (NumberFormatException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }     
       
}

/**
* 休眠
* @param sleepTime
*/
private void doSleep(long sleepTime){
   try{
    Thread.sleep(sleepTime);
   }catch(Exception e){
   }
}

抱歉!评论已关闭.