2012-01-06 26 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");