所以我有点困在一个程序,我必须读取一个文本文件,使用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();
}
}
}
}
答案 0 :(得分:0)
使用
byte [] bytes = new byte [size];
int byteCount;
while((byteCount = fstream.read(bytes))!= -1) ...
你可以这样简单地创建一个字符串:
new String(bytearray);
PS。因为某些原因而无法正常工作......