我怎么才能直接读出文件内容呢,比如文件是我爱你中华,我要读出的是文字,该如何操作
public static void printToString(String fileName) throws IOException {
int num = 0;
int count = 0;
byte[] buf = new byte[8*1024];
FileInputStream file;
try {
file = new FileInputStream(fileName);
while ((num = file.read(buf)) != -1) {
for (int i=0; i<num; ++i) {
if (++count%5 == 0)
System.out.println();
String st = new String(buf);
System.out.print(st + " ");
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("文件不存在!");
}
}String file = "C:\\Users\\Administrator\\Desktop\\1.txt";//文件路径 FileInputStream in = new FileInputStream(file); byte[] buf = new byte[20];//当字符串太长,就会放不下,你可以按需求设定长度,课程中用循环打印就是因为一次拿不完,循环来拿的 in.read(buf,0,buf.length); String s = new String(buf);//这个s就是“我爱你中华” System.out.println(s);