[英]How to open a file in a java program?
我的教授希望我們編寫一個程序,該程序將打開一個文件並讀取各行,他給出了這個例子。
import java.io.*;
import java.util.Scanner;
import java.io.IOException;
public class LineNumbers {
public static void main(String[] args) throws IOException
{
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Read lines from the file until no more are left.
while (inputFile.hasNext())
{
// Read the next name.
String familyName = inputFile.nextLine();
// Display the last name read.
System.out.println(familyName);
}
// Close the file.
inputFile.close();
keyboard.close();
}
}
問題是,一旦我運行該程序並告訴我輸入文件名,我應該鍵入什么? 如果我在桌面上制作了一個名為“ test”的隨機文本文件,並將“ test”輸入程序,它將無法打開它。 我是否應該鍵入一些特殊字符以將其打開並閱讀? 謝謝。
輸入文件的完整路徑。
如果您使用的是Windows,則可以通過按住Shift鍵 ,然后在文件上按鼠標右鍵單擊 ,然后選擇復制為路徑來獲取 。
您可以輸入帶有完整路徑的文件名:
C:\\\\ Path \\\\ To \\\\ The \\\\ File.txt
要么
/tmp/path/to/file.txt
或僅輸入文件名(假設它位於與可執行Java類相同的路徑下)。
如果路徑包含任何空格,則可能需要將文件名放在雙引號或雙引號之間。
您應該鍵入文件的路徑...如果您使用的是Windows,則應輸入類似
c:\\<path_to_desktop>\\test.txt (if it is a txt file)
在Linux上,您應該輸入類似
/<path_to_desktop>/test.txt
嘗試創建一個名為“ test.txt”的示例文件。向其中輸入一些值,例如“ Hello World”。關閉文件
注意->確保在Java程序所在的目錄中創建文件
現在,運行Java程序,當程序提示輸入文件名時,輸入text.txt(文件的完整名稱)
這應該運行並在控制台上打印文件的內容,這就是程序的作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.