2012-11-07 59 views
0

我想獲得我的Java程序的輸出寫入文件。寫出到控制檯以及文件

用戶輸入一些不應包含在文件中的數據。當程序響應時,它應該輸出信息給用戶,並且將SOLELY的輸出寫入文件。

從例子我已經在我的驅動程序類的頂部,這樣開始:

static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
static String lineFromOutput; 

這段代碼是在我可以從程序接收輸出的每一個地方:

try { 
    lineFromInput = in.readLine(); 
    FileWrite.write(lineFromInput); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

而它的呼叫是:

public class FileWrite { 
    public static void write(String message) { 
     PrintWriter out = null; 
     try { 
      out = new PrintWriter(new FileWriter("output.txt"), true); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     out.write(message); 
     out.close(); 
    } 
} 

它創建輸出文件,但多數民衆贊成它。程序的輸出沒有寫入。 我已經瀏覽了很多例子,這似乎是最簡單的方式讓球滾動,雖然我打開任何其他的建議。

謝謝!

+0

哪裏可以找到OutputtStreamReader的代碼? – rharrison33

+0

我已經稍微改變了一下代碼,我正在玩尋找其他選項並將該部分複製到帖子上。它應該是inputstreamreader – ZAX

+1

請修復代碼。你有lineFromInput和lineFromOutput。始終如一。這段代碼不應該編譯。 – rharrison33

回答

0

我覺得應該是InputStremReadert在下面的語句:

static BufferedReader in= new BufferedReader(new OutputtStreamReader(System.in)); 
static String lineFromOutput; 

由於

static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
static String lineFromOutput; 

編輯:這工作得很好。 請確保您通過輸入控制檯提供輸入。另請注意,它只讀取和寫入(覆蓋)單行。

public class FileWrite { 
     public static void write(String message) { 
       PrintWriter out = null; 
       try { 
        out = new PrintWriter(new FileWriter("output.txt"), true); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       out.write(message); 
       out.close(); 
     } 

     public static void main(String[] args){ 
      String lineFromInput; 
      try { 
       BufferedReader in = new BufferedReader(
              new InputStreamReader(System.in)); 
       lineFromInput = in.readLine(); 
       FileWrite.write(lineFromInput); 
       in.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 

編輯2:多線路輸入更新程序。 它不是每次寫入時打開和關閉文件的最佳方式,但是我只是試圖通過較小的更改來使您的程序工作。讓我知道,如果您需要建議避免重複打開/關閉輸出文件。

變化亮點:

  1. 讀取行,直到「退出」(改變爲所期望的字)的輸入
  2. 接收開啓在append模式的文件。

    public class FileWrite { 
        public static void write(String message) { 
          PrintWriter out = null; 
          try { 
           out = new PrintWriter(new FileWriter("output.txt", true), true); 
          } catch (IOException e) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          } 
          out.write(message); 
          out.close(); 
        } 
    
        public static void main(String[] args){ 
         String lineFromInput = ""; 
         try { 
          System.out.println("Provide the inputs in any number of lines"); 
          System.out.println("Type \"exit\" in new line when done"); 
          BufferedReader in = new BufferedReader(
               new InputStreamReader(System.in)); 
          while(!"exit".equals(lineFromInput)){ 
           lineFromInput = in.readLine(); 
           FileWrite.write(lineFromInput+System.lineSeparator()); 
          } 
          in.close(); 
         } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
        } 
    } 
    

EDIT3:使用Scanner讀取輸入您的更新程序:

 private static HashMap<Integer, Object> shapes = 
               new HashMap<Integer, Object>(); 
     static int i = 0; 

     public static void main(String[] args) { 
      PrintWriter output = null; 
      Scanner scanner = new Scanner(System.in); 
      try { 
       output = new PrintWriter(new FileWriter("output.txt"), true); 
      } catch (IOException e1) { 
       System.err.println("You don't have accress to this file"); 
       System.exit(1); 
      } 
      String command = ""; 
      while(!"quit".equalsIgnoreCase(command)){ 
       System.out.println("Enter your Command: "); 
       command = scanner.next(); 
       if (command.equalsIgnoreCase("create")) { 
        String type = scanner.next(); 
        if (type.equalsIgnoreCase("line")) { 
         double length = scanner.nextDouble(); 
         Line l = new Line(length); 
         scanner.nextLine();//flush the previous line 
         String line = scanner.nextLine(); 
         output.format("%s", line); 
         shapes.put(i, l); 
         i++; 
        }else if (type.equalsIgnoreCase("circle")) { 
         double radius = scanner.nextDouble(); 
         String color = scanner.next(); 
         Circle c = new Circle(radius, Colors.valueOf(color)); 
         scanner.nextLine();//flush the previous line 
         String line = scanner.nextLine(); 
         output.format("%s", line); 
         shapes.put(i, c); 
         i++; 
        }else if (type.equals("rectangle")) { 
         double length = scanner.nextDouble(); 
         double width = scanner.nextDouble(); 
         String color = scanner.next(); 
         Rectangle r = new Rectangle(length, width, 
         Colors.valueOf(color)); 
         scanner.nextLine();//flush the previous line 
         String line = scanner.nextLine(); 
         output.format("%s", line); 
         shapes.put(i, r); 
         i++; 
        }else if (type.equals("square")) { 
         double length = scanner.nextDouble(); 
         String color = scanner.next(); 
         Square s = new Square(length, Colors.valueOf(color)); 
         scanner.nextLine();//flush the previous line 
         String line = scanner.nextLine(); 
         output.format("%s", line); 
         shapes.put(i, s); 
         i++; 
        } 
       }else if (command.equals("printbyperimeter")) { 
        Shape[] shapeArray = shapes.values().toArray(new Shape[0]); 
        Arrays.sort(shapeArray); 
          System.out.println("Print in ascending order..."); 
        for (int j = 0; j < shapeArray.length; j++) { 
         Shape temp = shapeArray[j]; 
         if (temp.getClass().getName().equals("Line")) { 
          System.out.println("Shape: " 
            + temp.getClass().getName() + ", Perimeter: " 
            + temp.getPerimeter()); 
           } else { 
          System.out.println("Shape: " 
            + temp.getClass().getName() + ", Color: " 
            + ((Colorable) temp).getColor() 
            + ", Perimeter: " + temp.getPerimeter()); 
           } 
          } 
       }else if (command.equals("printbyarea")) { 
        Shape[] shapeArray = shapes.values().toArray(new Shape[0]); 
        System.out.println("Print in random order..."); 
        for (int j = 0; j < shapeArray.length; j++) { 
         Shape temp = shapeArray[j]; 
         if (!temp.getClass().getName().equals("Line")) { 
          System.out.println("Shape: " 
            + temp.getClass().getName() + ", Color: " 
            + ((Colorable) temp).getColor() + ", Area: " 
            + ((Areable) temp).getArea()); 
           } 
         } 
       }else if (command.equals("quit")) { 
        scanner.close(); 
        System.exit(0); 
       } 
      } 
      output.close(); 
     } 
+0

@DownVoter:請留下一些評論。 –

+0

'OutputtStreamReader'不存在。 'OutputStreamReader'也不是。 – Makoto

+0

@Makoto:是的,我知道。爲了避免OP搜索'InputtStreamReader'(有兩個t),我做了't'的註釋。這是downvote的原因嗎? –

0

嘗試使用的代碼。這個對我有用。您只需要更改文件路徑以匹配您想要輸出的位置。我在這裏使用BufferedWriter,我相信這是首選。

public static void main(String[] args) { 
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
String lineFromOutput; 

try { 
    lineFromOutput = in.readLine(); 
    FileWrite.write(lineFromOutput); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 



} 

public static class FileWrite { 
    private static void write(String message) throws IOException { 
     BufferedWriter out = null; 
    try { 
     out = new BufferedWriter(new FileWriter(new File("C:\\Users\\Teresa\\Dropbox\\output.txt"))); 
     //Replace the above line with your path. 
     out.write(message); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
     out.close(); 
    } 
} 
+0

它與我之前的方法有同樣的問題。該文件已創建,但文件中沒有任何內容 – ZAX

+0

我只是嘗試輸出一些行來查看outputfromline中是否有任何內容,通過在try和catch部分同時打印,既沒有打印任何內容,也沒有打印任何內容 – ZAX

+0

此代碼有效。你在更改文件路徑嗎?我已經測試過它。 – rharrison33

2

每次調用寫入打開和關閉文本文件。每次打開它都會被覆蓋,所以我希望只有最後一件東西被寫入纔會出現在文件中。

我建議從構造函數打開輸出文件,並從close方法關閉它。

+1

'new FileWriter(「output.txt」,true)'將打開文件,以便在最後添加新文本。 – madth3

+1

如果你這樣做,首先打開第二個參數爲false,以避免累積先前運行的數據。 –