请教两道java编程题,关于IO包的。

1,用旧IO包中的类打开并读取一个文本文件,每次读取一行内容。将每行作为一个String输入放入String数组里面打印这个数组。
2,用nio包实现上题。

希望结果能够直接运行成功,不胜感激!如果直接通过,会有加分。

nio不能实现一行一行读,只能一块一块读或者一个字符一个字符读。
代码如下:

import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class Main
{
public static void main(String[] args)
{
Main t = new Main();
t.ReadFlieByLine_IO("E:\\123.txt");
t.ReadFileByLine_NIO("E:\\123.txt");
}

public void ReadFlieByLine_IO(String Filename)
{
File file = new File(Filename);
BufferedReader reader = null;
try
{
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
//一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null)
{ //显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
/** finally {
if (reader != null){
try {
reader.close();
}
catch (IOException e1) {
}
}
}
*/
}

private void ReadFileByLine_NIO(String Filename)
{
FileInputStream file = null;
FileChannel reader = null;
try
{
file = new FileInputStream(Filename);
reader = file.getChannel();
String tempString = null;
ByteBuffer bb = ByteBuffer.allocate((int)reader.size());
reader.read(bb);
bb.flip();
String fileContent= new String(bb.array());
System.out.println(fileContent);
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
/** finally {
if (reader != null){
try {
reader.close();
}
catch (IOException e1) {
}
}
}
*/
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-04-22
package com;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Point {

public static void main(String[] args) {
Point p = new Point();
String path = "";// 你要读取的文件的路径 @example@
// "D:\\workspace\\JavaTest\\bin\\com\\a.txt"
p.outputMethod(path);
}

public void outputMethod(String path) {
try {
String[] arr = new String[1];
String[] temp;
BufferedReader br = new BufferedReader(new FileReader(path));
String line = br.readLine();
while (line != null) {
arr[arr.length-1] = line;
temp = new String[arr.length+1];
for(int i=0;i<arr.length;i++){
temp[i] = arr[i];
}
arr = new String[temp.length];
for(int i=0;i<arr.length;i++){
arr[i] = temp[i];
}
line = br.readLine();
}
br.close();
for(int i=0;i<arr.length-1;i++){
System.out.println(arr[i]);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}本回答被提问者采纳