• Java IO 之 RandomAccessFile 操作文件内容


    RandomAccessFile类实现对文件内容的随机读写


    文件内容的随机操作,重难点在于字符操作,具体查看API

     1 package org.zln.io.file;
     2 
     3 import java.io.IOException;
     4 import java.io.RandomAccessFile;
     5 
     6 /**
     7  * Created by coolkid on 2015/6/21 0021.
     8  */
     9 public class TestRandonAccessFile {
    10     public static void main(String[] args) throws IOException {
    11 //        fileReadTest();
    12         RandomAccessFile file = new RandomAccessFile("E:\测试文件.txt","rw");
    13 
    14         file.writeChars("filename");
    15 
    16         file.close();
    17 
    18     }
    19 
    20     private static void fileReadTest() throws IOException {
    21     /*文件刚打开 默认读取指针位置 位于 文件的最开始处 0 */
    22         RandomAccessFile file = new RandomAccessFile("E:\测试文件.txt","rw");
    23 
    24         System.out.println("文件大小:"+file.length()+" 字节");
    25 
    26         int c;
    27         for (int i = 0; i < 10; i++) {
    28             c = file.read();//读取一个字节 每次读取后文件指针往后移动一个位置
    29             System.out.println("单字节 - 第 "+i+" 次 读取:"+(char)c);
    30         }
    31 
    32         file.seek(0);
    33         byte[] bytes = new byte[100];
    34         for (int i = 0; i < 10; i++) {
    35             file.read(bytes);
    36             System.out.println("字节数组 - 第 "+i+" 次 读取:"+new String(bytes));
    37         }
    38 
    39         file.seek(0);
    40         String line;
    41         for (int i = 0; i < 10; i++) {
    42             line = file.readUTF();
    43             System.out.println("UTF - 第 "+i+" 次 读取:"+line);
    44         }
    45         file.close();
    46     }
    47 }
    E:GitHub oolsJavaEEDevelopLesson1_JavaSe_Demo1srcorgzlniofileTestRandonAccessFile.java
  • 相关阅读:
    linux常用命令
    linux下redis配置
    Git使用命令
    linux学习笔记
    NOPI读取Excel2003、Excel2007或更高级的兼容性问题
    netcore开发常用命令
    netcore3.0 dotnet ef执行报错
    vscode配置nuget常见问题
    PDMReader结合PowerDesigner导出word格式数据字典
    微信网页授权开发遇到问题
  • 原文地址:https://www.cnblogs.com/sherrykid/p/4592043.html
Copyright © 2020-2023  润新知