使用java在运行时文件中创建读取

时间:2012-01-06 10:01:05

标签: java runtime filereader

我使用java方法创建和编写文件,然后我想在运行时使用另一个java方法读取此文件。但是它会抛出java.io.FileNotFoundException错误。

我该如何解决此错误?

Writer output=null;
File file = new File("train.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(trainVal[0] + "\n");
-------------------
and read code

FileInputStream fstreamItem = new FileInputStream("train.tx");
        DataInputStream inItem = new DataInputStream(fstreamItem);
        BufferedReader brItem = new BufferedReader(new InputStreamReader(inItem));
        String phraseItem;
        ArrayList<Double> qiF = new ArrayList<Double>();

        while ((phrase = br.readLine()) != null) {
            //doing somethinh here
        }

2 个答案:

答案 0 :(得分:0)

使用正确的文件名。这包括文件的路径。还要确保没有人在这两个函数之间删除文件或重命名它。

答案 1 :(得分:0)

以下是读取文件的最佳方便方法之一。通过它而不是使用传统方法。


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

final public class Main
{
    public static void main(String... args)
    {
        File file = new File("G:/myFile.txt");   //Mention your absolute file path here.
        StringBuilder fileContents = new StringBuilder((int)file.length());
        Scanner scanner=null;
        try
        {
            scanner = new Scanner(file);
        }
        catch (FileNotFoundException ex)
        {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        String lineSeparator = System.getProperty("line.separator");

        try
        {
            while(scanner.hasNextLine())
            {
                fileContents.append(scanner.nextLine()).append(lineSeparator);
            }
        }
        finally
        {
            scanner.close();
        }
        System.out.println(fileContents);   //Displays the file contents directly no need to loop through.
    }
}

您在代码中提供了适当的文件扩展名时出错了。

FileInputStream fstreamItem = new FileInputStream("train.tx");

应该是

FileInputStream fstreamItem = new FileInputStream("train.txt");