有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我用一个java方法创建并编写一个文件,然后我想在运行时用另一个java方法读取这个文件。但它抛出了java。木卫一。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) 个答案

  1. # 1 楼答案

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

  2. # 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");