Java - 以“#”开头的字符串

Java - String that starts with '#'

提问人:VennaTT 提问时间:9/21/2023 最后编辑:rgettmanVennaTT 更新时间:9/21/2023 访问量:72

问:

有人可以向我解释一下,为什么我们需要在这段代码中写“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
Java 字符串 文件 if-statement 文本

评论

5赞 SuperStormer 9/21/2023
据推测,它允许以 .这绝不是必需的,但它对手写文件很有帮助。# comment
0赞 g00se 9/21/2023
是的,正如@SuperStormer所说,忽略评论。但是,您需要决定是读取资源还是任意定位的文件,因为这两种方式不能很好地混合
3赞 worpet 9/21/2023
这是你的代码,所以由你决定。如果您不想跳过以这样的行开头的行,或者不希望在输入中出现这样的行,则不必这样做。#
1赞 marcinj 9/21/2023
它可能用于注释掉行,您可以禁止它,但是如果某处存在带有注释掉的行的文件,那么您将遇到麻烦,因为您的代码可能无法加载它们。

答:

1赞 Divyansh Gemini 9/21/2023 #1

在循环中,我们正在检查以检查该行是否为注释。这样该行将被忽略。forline.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