编程真题邮寄包裹

Nio不能一行一行的读,只能一个一个的读或者一个一个字符的读。

代码如下:

导入Java . io . *;

导入Java . nio . *;

导入Java . nio . channels . file channel;

公共类Main

{

公共静态void main(String[] args)

{

Main t = new Main();

t.ReadFlieByLine _ IO(" E:\ \ 123 . txt ");

t.readfile byline _ NIO(" E:\ \ 123 . txt ");

}

public void ReadFlieByLine_IO(字符串文件名)

{

File file =新文件(文件名);

BufferedReader reader = null

尝试

{

System.out.println("以行为单位读取文件内容,一次一整行:");

reader = new buffered reader(new file reader(file));

String tempString = null

int line = 1;

//一次读取一行,直到读取null是文件的结尾。

while((tempString = reader . readline())!=空)

{//显示行号

system . out . println(" line "+line+":"+tempString);

line++;

}

reader . close();

}

catch (IOException e) {

e . printstacktrace();

}

/**最后{

如果(读者!= null){

尝试{

reader . close();

}

catch (IOException e1) {

}

}

}

*/

}

private void ReadFileByLine_NIO(字符串文件名)

{

FileInputStream file = null

FileChannel reader = null

尝试

{

file = new FileInputStream(文件名);

reader = file . get channel();

String tempString = null

byte buffer bb = byte buffer . allocate((int)reader . size());

reader . read(bb);

bb . flip();

String file content = new String(bb . array());

system . out . println(file content);

reader . close();

}

catch (IOException e) {

e . printstacktrace();

}

/**最后{

如果(读者!= null){

尝试{

reader . close();

}

catch (IOException e1) {

}

}

}

*/

}

}