2012-01-06 10 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

+0

ファイル名をダブルチェックしてください。入力ストリームを開く前に出力ストリームを閉じる(または少なくともフラッシュする)ことを確認してください。 – Thilo

+0

出力ストリームをフラッシュして、作成に使用したのと同じパスでファイルを読み込もうとしてください。これが役に立たなければ、いくつかのコードを表示する必要があります。 – A4L

答えて

0

正しいファイル名を使用してください。これにはファイルへのパスも含まれます。また、その2つの機能の間でファイルを削除しなかったか、名前を変更していないことを確認してください。

0

以下は、ファイルを読み取るための最も便利な方法の1つです。伝統的な方法を使用する代わりに、それを実行します。


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"); 
関連する問題