Java中如何一行行地读文件

Java中如何一行行地读文件,第1张

import java.io.BufferedReader

import java.io.File

import java.io.FileReader

import java.io.IOException

import java.io.InputStreamReader

public class ReadTest {

public static void main(String[] args) {

// 读控制台输入的文字!

BufferedReader br = null

String str = null

try {

br = new BufferedReader(new InputStreamReader(System.in))

while (true) {

str = br.readLine()

if (str.equals("886"))

break

System.out.println(str)

}

// 读文本文件..

br = new BufferedReader(new FileReader(new File("C:\\Users\\Administrator\\Desktop\\地址.txt")))

for (str = br.readLine() str != null str = br.readLine()) {

//打印你读的文本数据!

System.out.println(str)

}

} catch (IOException e) {

e.printStackTrace()

}

}

}

核心就是:readLine()方法,一行一行的读!

import java.io.File

import java.io.RandomAccessFile

/**

 * 读取文档的第二行内容

 *

 * @author 3306 2017年3月21日

 * @see

 * @since 1.0

 */

public class CountLine {

    /*

     * 读取文件绝对路径

     */

    private static String filePath = "d:/cms.sql"

    public static void main(String[] args) {

        long line = readLine(filePath)

        System.out.println(line)

    }

    /**

     * 读取文件行数

     * 

     * @param path

     *            文件路径

     * @return long

     */

    public static long readLine(String path) {

        long index = 0

        try {

            RandomAccessFile file = new RandomAccessFile(new File(path), "r")

            while (null != file.readLine()) {

                index++

            }

            file.close()

        } catch (Exception e) {

            e.printStackTrace()

        }

        return index

    }

}

package com.lwj.demo  

  

import java.io.* 

public class RandomAccessFileDemo {  

 public static void main(String[] args) throws Exception {  

    RandomAccessFile file = new RandomAccessFile("file", "rw")  

      // 以下向file文件中写数据  

  file.writeInt(20)// 占4个字节  

  file.writeDouble(8.236598)// 占8个字节  

  file.writeUTF("这是一个UTF字符串")// 这个长度写在当前文件指针的前两个字节处,可用readShort()读取  

  file.writeBoolean(true)// 占1个字节  

  file.writeShort(395)// 占2个字节  

  file.writeLong(2325451l)// 占8个字节  

  file.writeUTF("又是一个UTF字符串")  

  file.writeFloat(35.5f)// 占4个字节  

  file.writeChar('a')// 占2个字节  

  

  file.seek(0)// 把文件指针位置设置到文件起始处  

  

  // 以下从file文件中读数据,要注意文件指针的位置  

  System.out.println("——————从file文件指定位置读数据——————")  

  System.out.println(file.readInt())  

  System.out.println(file.readDouble())  

  System.out.println(file.readUTF())  

  

  file.skipBytes(3)// 将文件指针跳过3个字节,本例中即跳过了一个boolean值和short值。  

  System.out.println(file.readLong())  

  

  file.skipBytes(file.readShort()) // 跳过文件中“又是一个UTF字符串”所占字节,注意readShort()方法会移动文件指针,所以不用加2。  

  System.out.println(file.readFloat())  

   }

}

参考资料

http://blog.csdn.net/akon_vm/article/details/7429245


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/tougao/7926246.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-11
下一篇2023-04-11

发表评论

登录后才能评论

评论列表(0条)

    保存