[英]How to read from inputFileStream and split each line
我必須從看起來像mark;1001;3;4
輸入文件txtfile中讀取一個';'
每個變量之間。 如果它位於單獨的行中,我知道如何讀取,但是如果它位於同一行中,則無法讀取它。
這是我的開始方式:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.Buffer;
public class Try {
public static void main(String[] args) {
String Name;
int ID;
Double quiz1 , quiz2;
try {
FileInputStream fileIN = new FileInputStream("input.txt");
InputStreamReader inputST =new InputStreamReader(fileIN);
BufferedReader bufferRe = new BufferedReader(inputST);
String line;
while ((line = bufferRe.readLine()) != null) {
// I tried many things, but nothing worked for me.
// How could I use split here?
}
} catch (IOException e) {
System.out.println("input is not found ");
}
}
}
使用split是要走的路...
while ( ( line = bufferRe.readLine())!= null) {
for (String splitVal : line.split(";") {
//Do whatever you need to with the splitVal value.
//In you example it iterate 4 times with the values mark 1001 3 4
}
}
最簡單的解決方案(當您希望事情在換行符之間工作時也適用)是將Scanner
與;
一起使用;
作為其定界符:
Scanner s = new Scanner(bufferRe);
s.useDelimiter(";");
while (s.hasNext()) {
System.out.println(s.next());
}
-->
mark
1001
3
4
這也使您可以使用掃描儀方法進行操作。 輕松解析整數。
只需在循環內使用split方法即可將所有數據存儲在數組中。
String[] splited = line.split(";");
while ((line = bufferRe.readLine()) != null) {
for (String retval : line.split(";", 2)) {
System.out.println(retval);
}
}
輸出:
mark
1001;3;4
使用StreamTokenizer還有一個方法
try {
FileInputStream fis = new FileInputStream("input.txt");
Reader r = new BufferedReader(new InputStreamReader(fis));
StreamTokenizer st = new StreamTokenizer(r);
List<String> words = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
// print the stream tokens
boolean eof = false;
do {
int token = st.nextToken();
switch (token) {
case StreamTokenizer.TT_EOF:
System.out.println("End of File encountered.");
eof = true;
break;
case StreamTokenizer.TT_EOL:
System.out.println("End of Line encountered.");
break;
case StreamTokenizer.TT_WORD:
words.add(st.sval);
break;
case StreamTokenizer.TT_NUMBER:
numbers.add((int)st.nval);
break;
default:
System.out.println((char) token + " encountered.");
if (token == '!') {
eof = true;
}
}
} while (!eof);
} catch (IOException e) {
e.printStackTrace();
System.out.println("input is not found ");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.