栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java:从.txt文件中逐行读取字节

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java:从.txt文件中逐行读取字节

如果要操作任何类型的文件,请不要认为它们包含文本数据,而应将它们视为包含字节的二进制文件。使用输入和输出流读取和写入二进制文件。

这是一个读取文件并将其拆分为1024个字节的方法的示例,这些字节写入N个输出文件:

import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class FileSplit {    public static void main(String[] args) throws IOException {        new FileSplit().splitFile(new File(args[0]));    }    private void splitFile(File file) throws IOException {        FileInputStream fis = new FileInputStream(file);        try { byte[] buffer = new byte[1024]; // remaining is the number of bytes to read to fill the buffer int remaining = buffer.length;  // block number is incremented each time a block of 1024 bytes is read  //and written int blockNumber = 1; while (true) {     int read = fis.read(buffer, buffer.length - remaining, remaining);     if (read >= 0) { // some bytes were read         remaining -= read;         if (remaining == 0) { // the buffer is full  writeBlock(blockNumber, buffer, buffer.length - remaining);  blockNumber++;  remaining = buffer.length;         }     }     else {          // the end of the file was reached. If some bytes are in the buffer         // they are written to the last output file         if (remaining < buffer.length) {  writeBlock(blockNumber, buffer, buffer.length - remaining);         }         break;     } }        }        finally { fis.close();        }    }    private void writeBlock(int blockNumber, byte[] buffer, int length) throws IOException {        FileOutputStream fos = new FileOutputStream("output_" + blockNumber + ".dat");        try { fos.write(buffer, 0, length);        }        finally { fos.close();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453197.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号