4 回答

TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
假設(shè)您不知道格式如何,movies.txt
我建議您執(zhí)行以下操作:
將內(nèi)容附加到
StringBuilder
String
用的內(nèi)容做一個(gè)StringBuilder
得到想要的數(shù)據(jù)
這是一個(gè)小演示,對(duì)我有用。
//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.");
?}
這是我的內(nèi)容movies.txt
注意:
String
按照您想要的方式拆分內(nèi)容
如果你正確分割它
movies.length
會(huì)給你電影的數(shù)量
輸出

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
在這里,我為您準(zhǔn)備了工作代碼。它正在從 filereader 讀取文件,而 st 是等于每一行的參數(shù)。在循環(huán)中,它將遍歷每一行并計(jì)算行數(shù)。
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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
試試下面的代碼
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貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果您想嘗試,可以使用更簡(jiǎn)單的方式與文件交互:
List<String> lines = Files.readAllLines(Paths.get(path), Charset.defaultCharset());
之后,您可以與準(zhǔn)備好的所有行列表進(jìn)行交互,或者使用lines.size()
.
添加回答
舉報(bào)