集册 Java实例教程 使用RandomAccessFile读取文件

使用RandomAccessFile读取文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

594
使用RandomAccessFile读取文件

import java.io.*;
/**
 * N o w J a v a . c o m - 时代Java 提 供 
**/

import java.util.Vector;


public class ListOfNumbers2 {

    private Vector<Integer> victor;

    private static final int SIZE = 10;


    public ListOfNumbers2() {

        victor = new Vector<Integer>(SIZE);

        for (int i = 0; i < SIZE; i++)

            victor.addElement(new Integer(i));


        this.readList("infile.txt");

        this.writeList();

    }
/*from n  o  w  j  a  v  a . c o m*/

    public void readList(String fileName) {

        String line = null;

        try {

            RandomAccessFile raf = new RandomAccessFile(fileName, "r");

            while ((line = raf.readLine()) != null) {

                Integer i = new Integer(Integer.parseInt(line));

                System.out.println(i);

                victor.addElement(i);

            }

        } catch (FileNotFoundException fnf) {

            System.err.println("File: " + fileName + " not found.");

        } catch (IOException io) {

            System.err.println(io.toString());

        }

    }


    public void writeList() {

        PrintWriter out = null;


        try {

            out = new PrintWriter(new FileWriter("outfile.txt"));


            for (int i = 0; i < victor.size(); i++)

                out.println("Value at: " + i + " = " + victor.elementAt(i));

        } catch (ArrayIndexOutOfBoundsException e) {

            System.err.println("Caught ArrayIndexOutOfBoundsException: "

                    + e.getMessage());

        } catch (IOException e) {

            System.err.println("Caught IOException: " + e.getMessage());

        } finally {

            if (out != null) {

                System.out.println("Closing PrintWriter");

                out.close();

            } else {

                System.out.println("PrintWriter not open");

            }

        }

    }


    public static void main(String[] args) {

        new ListOfNumbers2();

    }

}


展开阅读全文