【问题标题】:Read created at runtime file with java读取在运行时使用 java 创建的文件
【发布时间】:2012-01-06 10:01:05
【问题描述】:

我使用 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
        }

【问题讨论】:

  • 仔细检查文件名。确保在打开输入流之前关闭(或至少刷新)输出流。
  • 确保刷新关闭输出流并尝试使用与创建文件相同的路径读取文件。如果这没有帮助,那么您必须显示一些代码。
  • 致所有反对者:对声誉低于 100 的人进行反对时要非常小心;这让我们看起来充满敌意。
  • 我检查了文件名是正确的。我关闭了流,以便创建文件并在其上写入。路径与我用来创建它的路径相同。
  • train.tx 应该是 train.txt,检查一下。

标签: java runtime filereader


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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


    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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多