如何从Java中的.txt文件读取部分文本? [英] How to read portions of text from a .txt file in Java?
问题描述
我想知道,有没有办法只读取.txt文件中的一部分字符串?例如,如果我的.txt文件中包含 1,5,10,20,我可以告诉Java只将 1保存到某个int,然后将 5保存到另一个int,依此类推吗?我希望我已经足够清楚了!
i was wondering, is there a way to read only parts of a String in a .txt file? Like for example, if "1,5,10,20" is in my .txt file, can i tell Java to save just "1" to a certain int, then save "5" to a different int, and so on? I hope i made it clear enough!
谢谢大家!
PS我知道如何阅读整行Java中使用BufferedReader编写的.txt文件中的文本,只是不是只读取其中的某些部分。
P.S i know how to read a whole line of text in a .txt file in Java using the BufferedReader, just not how to read only certain parts of it.
推荐答案
您可以使用 扫描仪
类,它提供了 Scanner#nextInt()
方法将下一个标记读取为int。现在,由于您的整数用逗号(,
)分隔,因此您需要设置逗号(,
)作为 Scanner
中的分隔符,它使用空白
字符作为默认分隔符。您需要使用 Scanner#useDelimiter(String)
方法。
You can use Scanner
class, which provides a Scanner#nextInt()
method to read the next token as int. Now, since your integers are comma(,
) separated, you need to set comma(,
) as delimiter in your Scanner
, which uses whitespace
character as default delimiter. You need to use Scanner#useDelimiter(String)
method for that.
您可以使用以下代码:
You can use the following code:
Scanner scanner = new Scanner(new File("demo.txt"));
scanner.useDelimiter(",");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
这篇关于如何从Java中的.txt文件读取部分文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!