从文件中读取每一行,并从中创建整数

发布于 2024-10-09 09:41:34 字数 125 浏览 2 评论 0原文

我有一个名为membercodes.cfg 的文件。 我想读取每一行(行是这样的:555:333:989)来读取。 然后,该线必须分成 3 部分。 整数1的值为555,整数2的值为333,整数3的值为989。

谢谢大家。

I have a file called membercodes.cfg.
I want to read each line (lines are like this: 555:333:989) to be read.
Then, the line must be split in 3 parts.
Integer 1 must be valued 555, Integer 2 valued 333, and Integer 3 valued 989.

Thank you all.

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

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

发布评论

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

评论(2

潦草背影 2024-10-16 09:41:34

与许多编程任务一样,这实际上是将一个“大”任务拆分为小任务:

  • 研究如何一次一行读取文件(查看 FileInputStream、InputStreamReader 、BufferedReaderBufferedReader.readLine;避免使用 FileReader,它始终使用平台默认字符编码 - 一个坏主意
  • )了解如何根据分隔符将一行拆分为不同的字符串(查看String.split
  • 了解如何将字符串解析为int(查看Integer.parseInt) )

正如另一个答案指出的那样,还有扫描仪。我自己使用 Scanner 的经验有些有限,但有时感觉有点像黑魔法,当事情没有按计划进行时很难调试。另一方面,它最终可能会减少代码。

无论您最终使用哪种解决方案,您都应该考虑两者...除了其他任何事情之外,这是一个有用的练习,可以像我所做的那样分解大任务,而且它也是一个学习 Java API 的各个部分是个好主意 - 包括“低级”API(例如我提到的 API)和高级 API(例如 Scanner)。

As with many programming tasks, this is really a matter of splitting one "big" task into small ones:

  • Work out how to read a file a line at a time (look at FileInputStream, InputStreamReader, BufferedReader, and BufferedReader.readLine; avoid FileReader, which always uses the platform default character encoding - a bad idea)
  • Work out how to split a line into different strings based on a delimiter (look at String.split)
  • Work out how to parse a String into an int (look at Integer.parseInt)

As another answer points out, there's also Scanner. My own experience with Scanner has been somewhat limited, but it sometimes feels a bit too much like black magic which is hard to debug when things don't go as planned. On the other hand, it may well end up with less code.

Whichever solution you end up using, you should probably look at both of them... aside from anything else, it's a useful exercise to break up the big task as I've done, and it's also a good idea to learn the various bits of the Java API - both the "low-level" APIs such as the ones I've mentioned, and the higher-level ones like Scanner.

挽袖吟 2024-10-16 09:41:34

您是否阅读过有关 扫描仪 的内容?

Have you read about Scanner ?

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