[英]java FileInputStream cannot find file
我在編碼 java 方面很新,我遇到了很多困難。 我想使用 bufferedreader 編寫一個從文件中讀取的程序,我已經創建了名為“scores.txt”的文件。 所以我有一個名為 processFile 的方法,它假設設置 BufferedReader 並循環遍歷文件,讀取每個分數。 然后,我需要將分數轉換為整數,將它們相加,並顯示計算出的平均值。
我不知道如何將它們相加並計算平均值,但我目前正在從文件中讀取數據。 它一直說它無法對文件進行優化,但我確信我的文檔中有一個名為“scores.txt”的文件。
這就是我目前所擁有的……這很糟糕。 我只是不太擅長這個 :( 也許有一個不同的問題?
public static void main(String[] args) throws IOException,
FileNotFoundException {
String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}
public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string
BufferedReader inputReader =
new BufferedReader (new InputStreamReader
(new FileInputStream(file)));
while (( line = inputReader.readLine()) != null){
System.out.println(line);
}
inputReader.close();
}
有兩個主要選項可用
使用文件的絕對路徑(從 Windows 中的驅動器號或 *.nix 中的斜杠開始)。 這對於“僅用於測試”的任務非常方便。
示例 Windows - D:/someFolder/scores.txt, *.nix - /someFolder/scores.txt
將文件放入項目根目錄,在這種情況下,類加載器將可以看到它。
將 score.txt 放在項目文件夾的根目錄中,或者將文件的完整路徑放在String file
。
該程序不知道檢查您的我的文檔文件夾中的scores.txt
如果您使用 IntelliJ,請在您的包中創建一個 input.txt 文件,然后右鍵單擊 input.txt 文件並單擊copy path
。 您現在可以使用該路徑作為輸入參數。
例子:
in = new FileInputStream("C:\\Users\\mda21185\\IdeaProjects\\TutorialsPointJava\\src\\com\\tutorialspoint\\java\\input.txt");
如果您在 eclipse 中,則從本地系統中獲取絕對路徑,然后右鍵單擊該文件並單擊屬性,您將獲得路徑復制並如下放置,這對我有用在 maven 項目中將屬性文件保存在 src/主要/資源`
私有靜態屬性 properties = new Properties();
public Properties simpleload() {
String filepath="C:/Users/shashi_kailash/OneDrive/L3/JAVA/TZA/NewAccount/AccountConnector/AccountConnector-DEfgvf/src/main/resources/sample.properties";
try(FileInputStream fis = new FileInputStream(filepath);) {
//lastModi = propFl.lastModified();
properties.load(fis);
} catch (Exception e) {
System.out.println("Error loading the properties file : sample.properties");
e.printStackTrace();
}
return properties;
}`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.