2012-01-06 24 views
-1

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

我该如何解决这个错误?

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 
     } 
+3

代码,请... – fge 2012-01-06 10:02:03

+0

仔细检查文件名。确保在打开输入流之前关闭(或至少刷新)输出流。 – Thilo 2012-01-06 10:03:43

+0

确保你刷新关闭你的outputstream并尝试用你用来创建它的相同路径读取文件。如果这没有帮助,那么你必须显示一些代码。 – A4L 2012-01-06 10:06:06

回答

0

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

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