开发者

Importing from Text File Java question

开发者 https://www.devze.com 2022-12-09 23:45 出处:网络
I decided to create a currency converter in 开发者_JAVA百科Java, and have it so that it would pull the conversion values out of a text file (to allow for easy editability since these values are consta

I decided to create a currency converter in 开发者_JAVA百科Java, and have it so that it would pull the conversion values out of a text file (to allow for easy editability since these values are constantly changing). I did manage to do it by using the Scanner class and putting all the values into an ArrayList.

Now I'm wondering if there is a way to add comments to the text file for the user to read, which Scanner will ignore. "//" doesn't seem to work.

Thanks


Best way would be to read the file line by line using java.io.BufferedReader and scan every line for comments using String#startsWith() where in you searches for "//".

But have you considered using a properties file and manage it using the java.util.Properties API? This way you can benefit from a ready-made specification and API's and you can use # as start of comment line. Also see the tutorial at sun.com.


Scanner wont ignore anything, you will have to remove the comments from your data after you have read it in.


Yea, while ((currentLine = bufferedReader.readLine()) != null) is possibly the easiest, then perform your necessary tests. currentLine.split(regex) is also very handy for converting a line into an array of values using a delimiter.


With Java nio, you could do something like this. Assuming you want to ignore lines that start with "//" and end up with an ArrayList.

List<String> dataList;
Path path = FileSystems.getDefault().getPath(".", "data.txt");
dataList = Files.lines(path)
             .filter(line -> !(line.startsWith("//")))
             .collect(Collectors.toCollection(ArrayList::new));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号