提问人:VennaTT 提问时间:9/21/2023 最后编辑:rgettmanVennaTT 更新时间:9/21/2023 访问量:72
Java - 以“#”开头的字符串
Java - String that starts with '#'
问:
有人可以向我解释一下,为什么我们需要在这段代码中写“line.indexOf('#') == 0”吗?我正在尝试从文本文件加载数据并创建对象。
Path path = Paths.get(getClass().getClassLoader().getResource("filmovi.txt").toURI());
//path is content of filmovi.txt
List<String> lines = Files.readAllLines(path, Charset.forName("UTF-8"));
//I put that content in List
for (String line : lines) {
line = line.trim();
if (line.equals("") || line.indexOf('#') == 0) //why we check '#'
continue;
String[] tokens = line.split(";");
Long id = Long.parseLong(tokens[0]);
String naziv = tokens[1];
int trajanje = Integer.parseInt(tokens[2]);
filmovi.put(Long.parseLong(tokens[0]), new Film(id, naziv, trajanje));
if(nextId<id)
nextId=id;
这是我尝试加载的文件的内容。我只是不明白为什么这个('line.indexOf('#') == 0')很重要?
1;The Shining;146
2;One Flew Over the Cuckoo's Nest;133
3;The Little Shop of Horrors;72
答:
1赞
Divyansh Gemini
9/21/2023
#1
在循环中,我们正在检查以检查该行是否为注释。这样该行将被忽略。for
line.indexOf('#') == 0
您也可以使用检查注释,两种方式都是正确的。line.charAt(0) == '#'
注释了代码以更好地解释每个语句:
// getting the complete path of 'filmovi.txt' file as Path's object
Path path = Paths.get(getClass().getClassLoader().getResource("filmovi.txt").toURI());
// getting all lines of the file as a List
List<String> lines = Files.readAllLines(path, Charset.forName("UTF-8"));
// iterating over each line in the List of lines
for (String line : lines) {
// removing extra spaces from beginning & end of each line
line = line.trim();
// if the line is empty (means it has no characters) or line's first character is '#' (means it is a comment)
if (line.equals("") || line.indexOf('#') == 0)
// then skipping further statements of the loop, & continuing for next line
continue;
// splitting the line by delimiter ';' & storing splitter parts into the array of String
String[] tokens = line.split(";");
// storing the line number (which is written in starting of each line) in a Long type variable
Long id = Long.parseLong(tokens[0]);
// storing the main text of the line in a String type variable
String naziv = tokens[1];
// storing the number written at the end of each line in int type variable
int trajanje = Integer.parseInt(tokens[2]);
...
}
0赞
g00se
9/21/2023
#2
如果要将输入视为资源,可以按如下方式执行此操作:
import java.util.Map;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class FilmParser {
public static void main(String[] args) throws Exception {
Map<Long, List<Film>> filmMap = null;
try (Scanner sc = new Scanner(FilmParser.class.getResourceAsStream("/films.csv"), "UTF-8").useDelimiter("\\R")) {
filmMap = sc.tokens()
.map(String::trim)
.filter(s ->!s.startsWith("#"))
.filter(s ->!s.isEmpty())
.map(Film::valueOfColonSV)
.collect(Collectors.groupingBy(Film::getId));
}
System.out.println(filmMap);
}
}
我为该类提供了一种方便的方法,用于从 CSV 创建实例Film
评论
# comment
#