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()
.
添加回答
举报