【问题标题】:Java - Divide text into chunks of n-bytesJava - 将文本分成 n 字节块
【发布时间】:2015-03-19 00:40:33
【问题描述】:

所以我有点卡在一个程序上,我必须读取一个文本文件,使用 FileInputStream 并将该文本分成 n 字节块。我必须发出一个 System.out.write();调用每个块,所以我想知道是否有一种简单的方法可以做到这一点。谢谢!

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.io.*;
import java.util.Scanner;


public class Test {

public static void main(String[] args) {

    int size=0;

    FileInputStream fstream = null;
    Scanner console = new Scanner(System.in);
    String inputFile = console.next();

    System.out.println("Chunk size?");
    Scanner in = new Scanner(System.in);
    size = in.nextInt();

    try {
        fstream = new FileInputStream(inputFile);

        System.out.println("Size in bytes : "
                + fstream.available());

        int content;

        while ((content = fstream.read()) != -1) {
            //System.out.write(); for every chunk of *size* bytes

        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fstream != null)
                fstream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
 }
}

【问题讨论】:

  • 只是为了澄清问题,我发出写入调用的意思是将每个不同的块写入控制台。
  • 不要添加评论 - 编辑您的问题。

标签: java parsing


【解决方案1】:
  1. 使用

    字节[]字节=新字节[大小];

    int byteCount;

    while((byteCount = fstream.read(bytes)) != -1) ...

  2. 您可以通过这种方式简单地创建一个字符串:

    新字符串(字节数组);

PS。抱歉缺少代码高亮显示,由于某种原因无法正常工作...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 2018-03-22
    相关资源
    最近更新 更多