Java创建文件并使用BufferedInputStream读取文件内容

/* 1、创建File类的对象 
   2、File.createFile() 方法创建新文件,若文件已经存在则返回false,创建成功返回true 
   3、使用FileInputStream读取文件文件内容,使用BufferedInputStream加速读取 
   4、无论上述步骤成功与否都要最后关闭相关的streams,在finally语句中关闭 
 */  
import java.io.*;  
public class Exercise {  
    
  public static void main(String args[]) {  
    try {  
      File file = new File("/home/zjz/Desktop/newFile.txt");  
      /* If file gets created then the createNewFile(), 
      method would return true or if the file is already present, 
      it would return false 
       */  
      boolean fvar = file.createNewFile();  
      if (fvar) {  
        System.out.println("File has been created successfully.");  
      } else {  
        System.out.println("File already present at the specified location");  
      }  
    } catch (IOException e) {  
      System.out.println("Exception Occurred: ");  
      e.printStackTrace();  
    }  
  
    try {  
      File file = new File("/home/zjz/Desktop/newFile.txt");  
      /* The delete() method returns true if the file is 
      deleted successfully else it returns false 
       */  
      if (file.delete()) {  
        System.out.println(file.getName() + " is deleted!");  
      } else {  
        System.out.println("Delete failed: File didn't delete successfully");  
      }  
    } catch (Exception e) {  
      System.out.println("Exception occured");  
      e.printStackTrace();  
    }  
  
    File file = new File("/home/zjz/Desktop/newFile.txt");  
    BufferedInputStream bis = null;  
    FileInputStream fis = null;  
    try {  
      // FileInputStream to read the file  
      fis = new FileInputStream(file);  
      /* Passed the FileInputStream to BufferedInputStream 
      for Fast read using the buffer array. 
       */  
      bis = new BufferedInputStream(fis);  
      /* available() method of BufferedInputStream 
      returns 0 when there are no more bytes present in 
      the file to be read. 
       */  
      while (bis.available() > 0) {  
        System.out.print((char) bis.read());  
      }  
    } catch (FileNotFoundException fnfe) {  
      System.out.println("The specified file not found");  
    } catch (IOException ioe) {  
      System.out.println("I/O Exception: " + ioe);  
    } finally {  
      try {  
        if (bis != null && fis != null) {  
          fis.close();  
          bis.close();  
        }  
      } catch (IOException ioe) {  
        System.out.println("Error in InputStream close(): " + ioe);  
      }  
    }  
  }  
   
}


From: http://beginnersbook.com/2014/01/how-to-write-to-a-file-in-java-using-fileoutputstream/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值