从文本文件导入Java问题

发布于 2024-08-09 19:16:41 字数 175 浏览 1 评论 0原文

我决定用 Java 创建一个货币转换器,并使用它从文本文件中提取转换值(以便轻松编辑,因为这些值不断变化)。我确实通过使用 Scanner 类并将所有值放入 ArrayList 来做到这一点。

现在我想知道是否有一种方法可以向文本文件添加注释供用户阅读,扫描仪会忽略该注释。 “//”似乎不起作用。

谢谢

I decided to create a currency converter in 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

十年九夏 2024-08-16 19:16:41

最好的方法是使用 逐行读取文件java.io.BufferedReader 并使用 String#startsWith() 在您搜索 "//"< 的位置/代码>。

但是您是否考虑过使用属性文件并使用 java.util.Properties API?这样您就可以从现成的规范和 API 中受益,并且可以使用 # 作为注释行的开头。另请参阅 sun.com 上的教程

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.

厌味 2024-08-16 19:16:41

扫描仪不会忽略任何内容,读入数据后,您必须从数据中删除注释。

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

好菇凉咱不稀罕他 2024-08-16 19:16:41

是的,虽然 ((currentLine = bufferedReader.readLine()) != null) 可能是最简单的,然后执行必要的测试。 currentLine.split(regex) 对于使用分隔符将行转换为值数组也非常方便。

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.

一笔一画续写前缘 2024-08-16 19:16:41

使用Java nio,你可以做这样的事情。假设您想忽略以“//”开头并以 ArrayList 结尾的行。

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

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文