【跟着imooc重学java】Java File IO读写操作

其实这篇文章其实和imooc一点关系都没有,但是为了让我的博客看起来不那么乱,我就放一起了。

写文件

  • 利用FileOutputStream写文件
public static void main(String[] args) throws IOException {
  //    创建一个File对象
  File file = new File("E:\\test\\test.txt");
  //    创建一个file对象的FileOutputStream对象
  OutputStream out = new FileOutputStream(file);
  //    创建一个FileOutputSteam对象的OutputStreamWriter对象,用于向文件中写入内容,并设置编码为 "UTF-8" 以便于写入中文字符且保证不会乱码
  OutputStreamWriter writer = new OutputStreamWriter(out,"UTF-8");
  //    添加内容到缓冲区中
  writer.append("English Test");
  //    该方法支持多次调用,"\r\n" 在文件中就是换行符
  writer.append("\r\n");
  writer.append("中文测试");
  //    该方法可以将缓冲区中的内容写入文件
  writer.flush();
  //    将缓冲区中的内容写入文件,并关闭写入流
  writer.close();
  //    关闭输出流(一定要关闭输出流,不然会影响你在其他地方的使用!)
  out.close();
}
  • 利用FileWriter写文件
public static void main(String[] args) throws IOException {
  //    创建一个File对象
  File file = new File("E:\\test\\test.txt");
  //    创建一个file对象的FileWriter对象
  FileWriter writer = new FileWriter(file); 
  //    添加内容到缓冲区中
  writer.append("English Test");
  //    该方法支持多次调用,"\r\n" 在文件中就是换行符
  writer.append("\r\n");
  writer.append("中文测试");
  //    该方法可以将缓冲区中的内容写入文件
  writer.flush();
  //    将缓冲区中的内容写入文件,并关闭写入流
  writer.close();
}

读文件

  • 利用FileInputStream读文件
public static void main(String[] args) throws IOException {
  //    创建一个File对象
  File file = new File("E:\\test\\test.txt");
  //    创建一个FileInputSteam对象
  InputStream in = new FileInputStream(file);
  //    创建一个InputStreamReader对象,编码要保持一致
  InputStreamReader reader = new InputStreamReader(in,"UTF-8");

  StringBuffer stringBuffer = new StringBuffer();
  //    利用循环来读取数据
  while(reader.ready()){
    //  因为read()方法的返回值是int型,所以需要使用char来强制转换
    stringBuffer.append((char)reader.read());
  }
  //    在console输出结果
  System.out.println(stringBuffer.toString());

  //    关闭reader&in对象,释放资源占用
  reader.close();
  in.close();
}
  • 利用FileReader读文件
public static void main(String[] args) throws IOException {
  //    创建一个File对象
  File file = new File("E:\\test\\test.txt");
  //    创建 FileReader对象
  FileReader reader = new FileReader(file); 
  //    创建一个字符数组用于存储即将从文件中读取到的内容
  char [] chars = new char[50];
  //    将文件中的内容读取到字符数组中
  reader.read(chars);
  for(char c : chars)
    System.out.print(c);
  //    关闭reader,释放资源
  reader.close();
}

备注:FileReader对象需要事前确定长度,而且如果长度大于其内容的长度,会被” “填充,所以不推荐用reader对象吧,如果有可以帮助我解决这个疑问的朋友,欢迎联系我,谢谢!

猜你喜欢

转载自blog.csdn.net/baofeidyz/article/details/78115425
今日推荐