在java中写入和读取文件

时间:2011-03-04 07:39:10

标签: java file-io

我正在尝试从文件中读取,取每行的长度,将长度写入另一个文件,然后打印第二个文件以查看写入结果,但是当我打开第二个文件时结果不是正是我想要的东西。运行此代码后,文件中有许多数字:

    String line = null;

    boolean flag = false;

    BufferedReader bf = new BufferedReader(new FileReader("c:\\lm_giga_5k_nvp_2gram.arpa"));

    BufferedWriter index = new BufferedWriter(new FileWriter("c:\\index.txt"));
    int l;

    int counter=0;

     while (( line = bf.readLine()) != null)

     {

        l=line.length();

        index.write( l + "\n" );

     }

     BufferedReader bf1 = new BufferedReader(new FileReader("c:\\index.txt"));

     String line1=null;

     while (( line1 = bf1.readLine()) != null)


     {
         System.out.println(line1);


     }

     bf.close();

     bf1.close();

请帮我使用这个例子。我关闭索引,但仍然有同样的问题。

注意:不要注意arpa文件,而是可以对txt文件进行成像。

2 个答案:

答案 0 :(得分:2)

你应该在打开另一个地方之前关闭index.txt;或者至少flush

... 
index.close();

BufferedReader bf1 = new BufferedReader(new FileReader("c:\\index.txt"));

String line1=null;
...

答案 1 :(得分:0)

这是Write和Read方法。您可以自定义它们以满足您的需求。

public boolean writePublic(String strWrittenString, String writeFileName, String writeEncoding, boolean appendString) {

    try {
        //System.out.println("Writing to file named " + writeFileName + " ...");
        Writer out = new OutputStreamWriter(new FileOutputStream(writeFileName, appendString), writeEncoding);
        try {
            out.write(strWrittenString);

        } finally {
            out.close();
        }

        //System.out.println("Writing to file named " + writeFileName + "- success.");
        return true;
    } catch (IOException ioe) {
        System.out.println("file named " + writeFileName + "-Failed. cause: " + ioe.getMessage());
        return false;
    } catch (Exception e23) {
        System.out.println("file named " + writeFileName + "-Failed. cause: " + e23.getMessage());
        return false;
    }

}

和Read方法:

public static String readWithoutEncoding(String readFileName) {
    StringBuilder text = new StringBuilder();
    try {
        //System.out.println("Reading from file named " + readFileName + " ...");

        String NL = System.getProperty("line.separator");
        Scanner scanner = new Scanner(new FileInputStream(readFileName));
        try {
            while (scanner.hasNextLine()) {
                text.append(scanner.nextLine() + NL);
            }
        } finally {
            scanner.close();
        }
    // System.out.println("Text read in: " + text);
    //System.out.println("Reading from file named " + readFileName + "- success.");
    } catch (IOException ioe) {
        System.out.println("file named " + readFileName + "-Failed. cause: " + ioe.getMessage());
    } catch (Exception e23) {
        System.out.println("file named " + readFileName + "-Failed. cause: " + e23.getMessage());


    } finally {
        return text.toString();
    }

}

另外,不要忘记在包含上述方法的Java类的开头放置所需的Import语句:

import java.io.*;
import java.util.Scanner;