4 回答

TA貢獻1891條經驗 獲得超3個贊
假設您不知道格式如何,movies.txt
我建議您執行以下操作:
將內容附加到
StringBuilder
String
用的內容做一個StringBuilder
得到想要的數據
這是一個小演示,對我有用。
//make sure you are using the "relative path" to find the movies.txt file(as follows)
?try (BufferedReader br = new BufferedReader(new FileReader("./movies.txt"))) {
? ? ? ?StringBuilder sb = new StringBuilder();
? ? ? ?String responseLine = null;
? ? ? ?while ((responseLine = br.readLine()) != null) {
? ? ? ? ? ? ? ? ? ? ?sb.append(responseLine.trim());
? ? ? ? }
? ? ? ? System.out.println(sb);
? ? ? ?//By now you should have all movies & titles to your StringBuilder instance then
? ? ? ? String temp = sb.toString();
? ? ? ? String movies[] = temp.split(" ");//split the string at "spaces"
? ? ? ? System.out.println("First Element: "+movies[0]);
? ? ? ? System.out.println("Second Element: "+movies[1]);
? ? ? ? System.out.println("Third Element: "+movies[2]);
? ? ? ? } catch (Exception e) {
? ? ? ? System.out.println("Could not find file.");
?}
這是我的內容movies.txt
注意:
String
按照您想要的方式拆分內容
如果你正確分割它
movies.length
會給你電影的數量
輸出

TA貢獻1942條經驗 獲得超3個贊
在這里,我為您準備了工作代碼。它正在從 filereader 讀取文件,而 st 是等于每一行的參數。在循環中,它將遍歷每一行并計算行數。
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
public class FileRead {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\Name\\Desktop\\test.txt");
String st;
BufferedReader br = new BufferedReader(new FileReader(file));
int count = 0;
while ((st = br.readLine()) != null) {
count++;
}
System.out.println(count);
}
}

TA貢獻1818條經驗 獲得超8個贊
試試下面的代碼
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class GuessTheMovie {
public static void main(String[] args) throws Exception {
try {
File file = new File("movies.txt");
Scanner scanner = new Scanner(file);
// open movies file and count the number of titles in the file
int count = 0;
while (scanner.hasNextLine()) {
count += 1;
scanner.nextLine();
}
System.out.println(count);
// create String array of movies such that the size is equal to the number of movies in file.
//String [] movies = []
} catch (Exception e) {
System.out.println("Could not find file.");
}
}
}

TA貢獻1829條經驗 獲得超6個贊
如果您想嘗試,可以使用更簡單的方式與文件交互:
List<String> lines = Files.readAllLines(Paths.get(path), Charset.defaultCharset());
之后,您可以與準備好的所有行列表進行交互,或者使用lines.size()
.
添加回答
舉報