从文本文件导入Java问题
我决定用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最好的方法是使用 逐行读取文件
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 usingString#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.
是的,虽然 ((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.
使用Java nio,你可以做这样的事情。假设您想忽略以“//”开头并以 ArrayList 结尾的行。
With Java nio, you could do something like this. Assuming you want to ignore lines that start with "//" and end up with an ArrayList.