我有一個名爲temperatures.txt的文件保存在我的桌面上,我會用什麼代碼將它帶入Java中。我目前正在嘗試如何從Java桌面調用文件?
File file = new File(「C:/ Windows/system32> /Desktop/temperatures.txt「);
當我拉起命令我的學校的計算機上,它說C:\ Windows \ System32下>
我的斜槓是倒退,因爲當我編譯它說:「\」是BlueJ的
我有一個名爲temperatures.txt的文件保存在我的桌面上,我會用什麼代碼將它帶入Java中。我目前正在嘗試如何從Java桌面調用文件?
File file = new File(「C:/ Windows/system32> /Desktop/temperatures.txt「);
當我拉起命令我的學校的計算機上,它說C:\ Windows \ System32下>
我的斜槓是倒退,因爲當我編譯它說:「\」是BlueJ的
非法字符/
是一個正斜槓。它是基於Unix的操作系統中的路徑分隔符。
\
是反斜槓。它是Windows中的路徑分隔符。但兩者都應該有效。 Java會很好地翻譯。
在Java中的字符串文字\
(以及類似的其他大多數編程語言)是一個轉義字符。當你將字符串文字寫爲"C:\Windows..."
你的IDE抱怨是因爲Java試圖把「\ W」當作轉義序列。
輸入一個字符串中的反斜槓字符文字,你需要用一個反斜槓轉義反斜線。所以,用\\
代替\
。
File file = new File("C:\\Windows\\system32>\\Desktop\\temperatures.txt");
另一種完整的解決方案:
import java.io.File;
import java.io.IOException;
public class Programme {
public static void main(String[] args) {
String yourDesktopPath = System.getProperty("user.home") + "\\Desktop\\";
try {
File file = new File(yourDesktopPath + "temperatures.txt");
if (file.createNewFile()) {
System.out.println("File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
這是確定以使用斜槓而不是反斜槓。您可以使用\\
作爲反斜槓,但這不會改變任何內容。
我看到3個可能的路徑問題。
1)該路徑包含字符>
,似乎它不屬於那裏。它可能應該是:
File file = new File("C:/Windows/system32/Desktop/temperatures.txt");
2)windows\system32
是一個系統目錄,它可能是窗戶限制訪問該文件夾。
3)這不是普通的桌面目錄。通常桌面在用戶目錄中。例如這裏:
C:\Users\YourName\Desktop
我還有:java.io.FileNotFoundException:C:\ WINDOWS \ SYSTEM32 \桌面\ temperatures.txt(系統找不到指定的路徑) – Alex 2014-10-01 01:31:41
我敢肯定,路徑錯誤。 – 2014-10-01 01:32:28