Java-将文本分成n字节的块 [英] Java - Divide text into chunks of n-bytes

查看:63
本文介绍了Java-将文本分成n字节的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I am kinda stuck on a program where I have to read a text file, using FileInputStream and divide that text into chunks of n-bytes. I have to issue one System.out.write(); call for each chunk, so I am wondering if there is a simple way to do this. Thanks!

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();
        }
    }
 }
}

推荐答案

  1. 使用

  1. use

byte []个字节=新的byte [size];

byte[] bytes = new byte[size];

int byteCount;

int byteCount;

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

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

您可以通过以下方式简单地创建一个字符串:

you can simply create a string this way:

新字符串(bytearray);

new String(bytearray);

PS.抱歉缺少突出显示的代码,由于某种原因无法正常工作...

PS. sry for the missing codehighlighting, didn't work properly for some reason...

这篇关于Java-将文本分成n字节的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆