纪录一下解决java.io.EOFException的方法
- package onlyfun;
- import java.io.*;
- import java.util.*;
- public class Test_5 {
- List<String> list = new ArrayList<String>();
- DataOutputStream dos = null;
- OutputStream out = null;
- DataInputStream dis = null;
- InputStream is = null;
- public static void main(String[] args) {
- new Test_5();
- }
- public Test_5() {
- list.add("first");
- list.add("second");
- list.add("third");
- write();
- List<String> ret = read();
- Iterator it = ret.iterator();
- while(it.hasNext()) {
- String temp = (String)it.next();
- System.out.println(temp);
- }
- }
- public void write() {
- try {
- out = new FileOutputStream("test.txt");
- dos = new DataOutputStream(out);
- for(int i=0; i<list.size(); i++) {
- String str = list.get(i);
- dos.writeUTF(str);
- }
- if(out != null) {
- out.close();
- out = null;
- }
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public List<String> read() {
- List<String> ret = new ArrayList<String>();
- try {
- is = new FileInputStream("test.txt");
- dis = new DataInputStream(is);
- String temp = null;
- temp = dis.readUTF();
- while(temp != null) {
- ret.add(temp);
- if(dis.available()>0) {
- temp = dis.readUTF();
- }
- else {
- break;
- }
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return ret;
- }
- }
以下为出错时的代码:read()方法
- public List<String> read() {
- List<String> ret = new ArrayList<String>();
- try {
- is = new FileInputStream("test.txt");
- dis = new DataInputStream(is);
- String temp = null;
- temp = dis.readUTF();
- while(temp != null) {
- // ret.add(temp);
- // if(dis.available()>0) {
- // temp = dis.readUTF();
- // }
- // else {
- // break;
- // }
- ret.add(temp);
- temp = dis.readUTF();
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return ret;
- }