开发者

How to restore a text file?

I want to restore the following data from the text fi开发者_开发问答le. The problem is only one string/line I can restore, I can't restore the rest of the data.

Here's the code :

public static String restore(String filename) throws IOException, ClassNotFoundException
{
    FileInputStream fn = new FileInputStream(filename);
    ObjectInputStream ob = new ObjectInputStream(fn);
    String sample = (String) ob.readObject();

     return sample;
}


It is hard to understand the meaning of this question, but if you just want to read lines from a .txt file and into an array, then these two methods might help.

You just need to call String[] textArray = readFromFile("yourfilename.txt"); This gives you an array with each line in the file as an element.

Scanner fScan(String filename) {

        Scanner sc = null;
        try {
            sc = new Scanner(new File(fname));
        } catch (FileNotFoundException e) {
            System.out.println("File not found:" + fname + "  " + e);
        }
        return sc;
}

String[] readFromFile (String fname) {
        Scanner sc = fScan(fname);
            int length = 0;
            String lineCounter;
        while (sc.hasNext()){
            lineCounter = sc.nextLine();
            length++;
        }

        String[] array = new String[length];

        sc = fScan(fname);

        for (int i = 0; i < length; i++) {
        array[i] = sc.nextLine();
        }

        sc.close();
        return array;
}


Your code does only read the first Element within your binary file.

public static void restore(String filename) throws IOException, ClassNotFoundException
{
    FileInputStream fn = new FileInputStream(filename);
    ObjectInputStream ob = new ObjectInputStream(fn);
    String string1 = (String) ob.readObject();
    String string2 = (String) ob.readObject();

}

Are you sure you did not overwrite your file while serializing it?

But as far as I understand your Question you don't want to serialize/deserialize a String-Object, rather than reading/writing a textfile.

If you just want to read/write a file, you are on the wrong way with the ObjectInputStream.

ake a look at: http://download.oracle.com/javase/1.3/docs/api/java/io/BufferedReader.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜