zoukankan      html  css  js  c++  java
  • 文件的读写,FileOutputStream和FileInputStream

    实现功能:向一个.txt文本文件写入文本内容,并读取该文本文件的内容。
    我将以上功能封装成了一个Txt类,以下是该类的代码实现。

     1 public class Txt {
     2     public static int length;
     3 
     4     public Txt() {}
     5 
     6     public static void writeTxt(File file, String content) {
     7         try {
     8             //实例化一个写入file文件的FileOutputStream
     9             FileOutputStream fops = new FileOutputStream(file);
    10             //字符串转换为byte[]
    11             byte[] txtbytes = content.getBytes();
    12             length = txtbytes.length;
    13             //向文件输出流fops写入byte[]
    14             try {
    15                 fops.write(txtbytes);
    16                 fops.close();
    17             } catch (IOException e) {
    18                 e.printStackTrace();
    19             }
    20         } catch (FileNotFoundException e) {
    21             e.printStackTrace();
    22         }
    23     }
    24 
    25     public static String readTxt(File file) {
    26         String string = null;
    27         byte[] txtbytes = new byte[length];
    28         try {
    29             //实例化一个读取file文件的FileInputStream
    30             FileInputStream fips = new FileInputStream(file);
    31             try {
    32                 //从文件输入流里面读取txt数据,存入byte[]
    33                 int result = fips.read(txtbytes, 0, txtbytes.length);
    34                 //将byte[]转换为string
    35                 string = new String(txtbytes);
    36             } catch (IOException e) {
    37                 e.printStackTrace();
    38             }
    39         } catch (FileNotFoundException e) {
    40             e.printStackTrace();
    41         }
    42         return string;
    43     }
    44 }
  • 相关阅读:
    Java ListIterator(迭代器)
    java 异常 throw
    java iterator(迭代器)
    java list
    type Iterator does not take parameters
    Java 容器的打印
    java 添加一组元素
    Java 容器的基本概念
    软件
    java 学习网站
  • 原文地址:https://www.cnblogs.com/gxclmx/p/6905164.html
Copyright © 2011-2022 走看看