簡體   English   中英

我希望Java使用…new PrintStream創建一個新文件……一切正常,但是我在項目中找不到該文件

[英]I want java to create a new file with …new PrintStream… it all works fine, but I can't find the file in my project

因此,我有一個類似於數字數學測試的簡單代碼(盡管只有1個問題)。 我希望程序掃描在輸入窗口中鍵入的內容,並在新文本文件中打印結果是對還是錯。 問題是我無法在eclipse中的項目中找到文本文件,而是必須找到我的項目文件夾並在其中找到.txt文件。 是否可以使.txt文件在Eclipse中的項目內部可見? 謝謝! ...另外,如何在Java中的引號內做引號? 我的意思是像“您回答“ 500””。

package Default;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;

public class MathTest {
  public static void main(String args[])
                throws FileNotFoundException {
    String Canswer = "270";
    String X;

    PrintStream file = new  PrintStream(new File("Test results.txt"));
    Scanner scan = new Scanner(System.in);

    System.out.println("This is a test, please answer the question correctly.");
    System.out.println("What is 50*50/100-20+(800/20) ?");

    X = scan.nextLine();

    System.out.println("That concludes this test, your test results will be available"
        + " in ´Test results.");

    if (X.equals(Canswer)) {
      file.println("You answered " + X);
      file.println("That is correct, well done!");
    } else {
      file.println("You answered " + X + ".");
      file.println("The correct answer was " + Canswer);
      file.println("You have failed this test.");
    }
  }
}

關於看不到文件的第一個直覺是,您沒有刷新項目。 嘗試右鍵單擊您的項目>單擊“刷新”,然后查看您的文本文件是否出現。 Eclipse不會實時更新文件系統,因此您必須刷新項目以查看任何更新。

對於引號,您必須使用前面的正斜杠對引號進行轉義,如下所示:

System.out.println("She said, \"I don't eat vegetables.\"");

將會輸出:

她說:“我不吃蔬菜。”

將文件放在eclipse中的項目基礎目錄中,然后僅使用名稱訪問文件。

您需要在項目目錄文件夾(在src文件夾之外)內指定文件,然后按名稱(如果需要,還可以輸入類型)進行訪問。

唯一需要指定路徑的時間是將文件存儲在子目錄(例如“ resources / images / player / player_player_forward.png”)中還是不在.jar中。

另外,為了在Java中的String中顯示引號,請在引號之前放置一個反斜杠。

例如:

String quote = "\"Life is like a box of chocolates.\"";

它將打印出:

“生活就像一盒巧克力。”

另外,就像使用換行符一樣:

String text = "Hello.\nHow is your day?"

那將打印:

“你好,今天過得如何?”

如果要打印實際的反斜杠,請在反斜杠之前進行反斜杠。

根據您所使用的操作系統, PrintStream file = new PrintStream(new File("Test results.txt")); 可能是由於空間問題。 也就是說,為什么要使用PrintStream而不是BufferedWriter?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM