Java文件输入输出流实战:读写操作示例

原创 超、凢脫俗 2024-09-19 16:27 148阅读 0赞

在Java中,我们通常使用FileInputStream和FileOutputStream来进行文件的读写操作。下面是一些具体的操作示例:

  1. 读取文件
    1. try (FileInputStream fis = new FileInputStream("example.txt"));) {
    2. byte[] buffer = new byte[1024]; // 一次性读取1KB
    3. int read;
    4. while ((read = fis.read(buffer))) != -1) { // 如果不为空,继续读取
    5. System.out.println(new String(buffer, 0, read))));
    6. }
    7. } catch (IOException e) {
    8. e.printStackTrace();
    9. }
  2. 写入文件
    1. try (FileOutputStream fos = new FileOutputStream("example.txt"));) {
    2. String content = "Hello, World!"; // 要写入的内容
    3. fos.write(content.getBytes()); // 写入内容
    4. fos.flush(); // 清理缓存,确保数据已写入磁盘
    5. } catch (IOException e) {
    6. e.printStackTrace();
    7. }
    注意:在实际使用中,需要处理可能发生的IOException。此外,写文件后记得关闭流。
文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,148人围观)

还没有评论,来说两句吧...

相关阅读