zoukankan      html  css  js  c++  java
  • dm

    import java.io.*;
    import java.util.ArrayList;
    import java.util.List;
    
    public class MyHead {
        //Main函数,程序入口
        public static void main(String[] args)
        {
            //调用读取方法,定义文件以及读取行数
            readLine(new File("C:\test\你的学号.txt"), 10);
        }
        public static List<String> readLine(File file, long numRead)
        {
            // 定义结果集
            List<String> result = new ArrayList<String>();
            //行数统计
            long count = 0;
            // 排除不可读状态
            if (!file.exists() || file.isDirectory() || !file.canRead())
            {
                return null;
            }
            // 使用随机读取
            RandomAccessFile fileRead = null;
            try
            {
                //使用读模式
                fileRead = new RandomAccessFile(file, "r");
                //读取文件长度
                long length = fileRead.length();
                //如果是0,代表是空文件,直接返回空结果
                if (length == 0L)
                {
                    return result;
                }
                else
                {
                    //初始化游标
                    long pos= 0;
                    while (count < numRead)
                    {
                        //开始读取
                        fileRead.seek(pos);
                        //如果读取到
    代表是读取到一行
                        if (fileRead.readByte() == '
    ')
                        {
    
                            //使用readLine获取当前行
                            String line = fileRead.readLine();
                            //保存结果
                            result.add(line);
    
                            //打印当前行
                            System.out.println(line);
                            //行数统计,如果到达了numRead指定的行数,就跳出循环
                            count++;
    
                        }
                        pos++;
                    }
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (fileRead != null)
                {
                    try
                    {
                        //关闭资源
                        fileRead.close();
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
    
            return result;
        }
    }
    
    
  • 相关阅读:
    NIO 学习笔记
    Spring Boot 学习笔记
    Java集合框架
    StringBuffer&StringBuilder类
    String 类
    Java 重写 hashCode() 和 equals() 方法
    Java 基本数据类型 && 位运算
    [SequenceFile_1] Hadoop 序列文件
    Windows 下端口被占用
    Java 反射机制
  • 原文地址:https://www.cnblogs.com/KY-high/p/8906925.html
Copyright © 2011-2022 走看看