JavaIO流学习总结-FileOutputStream和FileInputStream基本操作练习

package io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 /*
  * 修改日期:2020/03/30
  * 修改人:牟松
  * FileOutputStream和FileInputStream基本操作练习
  */
class Tool {
    File file=new File("D:\\Ceshi.txt");
 FileOutputStream outputstream=null;
 FileInputStream intputstream=null;
 
 
 //读文件中内容
 public void read() throws IOException
 {
  try {
   byte[] bytes=new byte[10];
   intputstream=new FileInputStream(file);
   //根据bytes的大小读出相应大小的字节流数据
   intputstream.read(bytes);
     /*
      * 第一个参数为byte数组,第二个参数0是从byte数组的下标0开始,第三个参数是读入的字节数为10
      * 换行符占一个字节,不同的编码方式可能不同,需要根据实际情况确定
      */
   intputstream.read(bytes,0,10);
   String str = new String(bytes);
   System.out.println(str);
   intputstream.close();
  } catch (FileNotFoundException e) {
   System.out.println("文件不存在或者无操作权限,读取失败!");
   e.printStackTrace();
  }
 }
 
 //往文件中写内容
 public void write() throws IOException
 {
  try {
   file.createNewFile();
   outputstream=new FileOutputStream(file);  //加入参数true则为添加,否则为覆盖
   String ceshi="测试文本,测试文本\n测试文本,测试文本";
   //将文本全部写入
   outputstream.write(ceshi.getBytes());
    /*
     * 第一个参数为byte数组,第二个参数6是从byte数组的下标6开始,第三个参数是写入的字节数为10
     * 换行符占一个字节,不同的编码方式可能不同,需要根据实际情况确定
     */
   outputstream.write(ceshi.getBytes(), 6, 10);
   outputstream.close();
  } catch (FileNotFoundException e) {
   System.out.println("文件不存在或者无操作权限,写入失败!");
   e.printStackTrace();
  }  
 }
}
public class Ceshi {
   public static void main(String[] args)
     {
    Tool tool=new Tool();
    try {
       //操作内容
       tool.read();
    } catch (IOException e) {
  e.printStackTrace();
    }
     }
}

猜你喜欢

转载自www.cnblogs.com/musong1998/p/12600954.html