问题
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!
Thanks guys!
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.
回答1:
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());
}
回答2:
The Scanner class has a set of hasNextXyz() and nextXyz() methods that can be used to pick and convert values separated by some delimiter.
String lineOfInts = "1,5,10,15,20";
Scanner scanner = new Scanner(lineOfInts).useDelimiter(",");
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt());
}
See Scanner#nextInt() for more info.
来源:https://stackoverflow.com/questions/17708760/how-to-read-portions-of-text-from-a-txt-file-in-java