2016-10-04 44 views
0

我想知道是否有人可以看看我的代碼,看看我做錯了什麼。我試圖讓我的程序寫入一個文件,但它不會。我需要一些幫助才能將結果寫入文件。是的,我知道很多問題已經被問及這個問題,是的,我看着他們,有不少。我只是不能真正使用它對我沒有意義的例子。任何幫助都會很棒。java寫入文件不起作用

import java.util.Scanner; 
import java.io.*; 

public class DistanceFile {  
    public static void main(String[] args) throws IOException { 
     int time; //hours traveled 
     int hour;//for the formula 
     String FileName; 
     Scanner scanner= new Scanner(System.in); 
     System.out.println("Enter the speed of the vehicle"); 
     int speed= scanner.nextInt(); 
     while (speed<=0){ 
      System.out.println("Please enter a valid speed"); 
      speed=scanner.nextInt(); 
     } 
     System.out.println("Enter the number of hours traveled"); 
     time=scanner.nextInt(); 
     while (time<=0){ 
      System.out.println("Please enter a valid time"); 
      time=scanner.nextInt(); 
     } 
     hour=0; 

     PrintWriter outputFile= new PrintWriter("DistanceFile.txt"); 
     for( hour = 1; hour <= time; hour++) 
      System.out.println(hour+ " " + (hour * speed)); 
     outputFile.print(speed+""); 
     outputFile.print(time+" "); 
     outputFile.close(); 
+1

outputFile.flush()在關閉之前 – Erik

+0

'close()'方法應該進行刷新。什麼是錯誤?該文件根本沒有被創建,或者被創建並且不包含預期的輸出? – PNS

+0

該代碼似乎爲我工作(DistanceFile.txt在工作目錄中創建) –

回答

0

您的代碼工作正常。你應該輸入整個文件路徑:

PrintWriter outputFile= new PrintWriter("C:\\Users\\XXX\\Desktop\\test.txt"); 
0

檢查出BufferedWriter

即使在調整好代碼之後,它仍然不起作用,請檢查您保存的位置是否可以寫入。如果您的程序不被允許,您可以保存在不同的地方或修改文件夾設置。

+0

我很新這個謝謝你 –