io流读写操作

 

  /** 
       *  
       * DOC 将F盘下的test.jpg文件,读取后,再存到E盘下面. 
       *  
       * @param args 
       * @throws Exception 
       */  
      public static void main(String[] args) throws Exception {  
          FileInputStream in = new FileInputStream(new File("D:\Buttom.gif"));// 指定要读取的图片  
          FileOutputStream out = new FileOutputStream(new File("E:\Buttom.gif"));// 指定要写入的图片  路径 以及 后缀名
          int n = 0;// 每次读取的字节长度  
          byte[] bb = new byte[1024];// 存储每次读取的内容  
          while ((n = in.read(bb)) != -1) {  
              out.write(bb, 0, n);// 将读取的内容,写入到输出流当中  
          }  
          out.close();// 关闭输入输出流  
          in.close();  
      } 

 

         /**

  •      * DOC 从文件里读取数据.
  •      *
  •      * @throws FileNotFoundException
  •      * @throws IOException
  •      */ 
  •     private static void readFromFile() throws FileNotFoundException, IOException { 
  •         File file = new File("E:\helloworld.txt");// 指定要读取的文件 
  •         FileReader reader = new FileReader(file);// 获取该文件的输入流 
  •         char[] bb = new char[1024];// 用来保存每次读取到的字符 
  •         String str = "";// 用来将每次读取到的字符拼接,当然使用StringBuffer类更好 
  •         int n;// 每次读取到的字符长度 
  •         while ((n = reader.read(bb)) != -1) { 
  •             str += new String(bb, 0, n); 
  •         } 
  •         reader.close();// 关闭输入流,释放连接 
  •         System.out.println(str); 
  •     }

          /**

  •      * DOC 往文件里写入数据.
  •      *
  •      * @throws IOException
  •      */ 
  •     private static void writeToFile() throws IOException { 
  •         String writerContent = "hello world,你好世界";// 要写入的文本 
  •         File file = new File("E:\helloworld.txt");// 要写入的文本文件 
  •         if (!file.exists()) {// 如果文件不存在,则创建该文件 
  •             file.createNewFile(); 
  •         } 
  •         FileWriter writer = new FileWriter(file);// 获取该文件的输出流 
  •      writer.write(writerContent);// 写内容 
  •         writer.flush();// 清空缓冲区,立即将输出流里的内容写到文件里 
  •         writer.close();// 关闭输出流,施放资源 
  •     } 
原文地址:https://www.cnblogs.com/yy123/p/4170444.html