[英]Just read numbers in line from file
我在名為avar.txt的文件中有一行行。 在文件中,我嘗試讀取不是以'£'開頭的數字。 為此,我編寫了以下代碼,但是,我不知道如何在其中獲取數字。 是否可以直接從文件中獲取編號而不是我的方法,實際上我的方法不起作用?
£Life <--------------- do not read
£No File Name Contents <--------------- do not read
00 life.all ...
£01 life.prt ... <--------------- do not read
03 life.all ...
11 life.pl ...
£Expectation <--------------- do not read
£No File Name Contents <--------------- do not read
13 expectation.ops ...
04 expectation.at ...
£05 expectation.anil ... <--------------- do not read
預期閱讀次數; 00、03、11、13、04
只是要注意,每個數字前面都帶有制表符,例如<tab(ie whitespace)><number>
我無法使用的代碼,(我不知道如何從中提取數字)
FileReader file = new FileReader("avar.txt");
BufferedReader read = new BufferedReader(file);
for( String tmp = null ; tmp = read.readLine() != null;){
number.add(tmp);
}
我假設您只想使用該號碼。如果您想使用其余的號碼,請更新您的帖子,我會更新答案。
因此,僅對於數字,您可以執行以下操作:
Scanner in = new Scanner(new FileInputStream("Avar.txt"));
while(in.hasNextLine){
Scanner lineScanner = new Scanner(in.nextLine());
if(lineScanner.hasNextInt()){
int x = lineScanner.nextInt();
// do something with x
}
}
這將逐行讀取您的輸入。 對於每一行,如果該行以int開頭(以"£01"
開頭的行不是以int開頭),則該int
將存儲在變量x
。 之后,您可以做w / e。 如果您想要它們,可以將它們傳遞到Array
等中。
BufferedReader
版本:
BufferedReader file = new BufferedReader(new FileReader("Avar.txt"));
String line;
while((line = file.readLine()) != null){
if(line.charAt(0) >= 48 && line.charAt(0) <= 57 ){
String number = line.substring(0, 2);
int x = Integer.valueOf(number);
//do something with x
}
}
file.close();
與Scanner
版本的邏輯相同。
希望這可以幫助
FileReader file = new FileReader("avar.txt");
BufferedReader read = new BufferedReader(file);
for( String tmp = null ; tmp = read.readLine() != null;){
String [] strNumArray = tmp.split(" ");
number.add(strNumArray[0]);
}
通過將行拆分成由空格符號分隔的部分,可以達到上述要求。
你可以這樣
File ifile = new File("avar.txt");
FileReader fr = new FileReader(ifile.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
for (String line = br.readLine(); line != null; line = br.readLine()) {
if (!line.startsWith("£")) {
...... Type your code.....//it takes line without "£" sign.
}
}
如果您只想要這樣的數字。
Scanner in = new Scanner("Avar.txt");
while(in.hasNextInt)
{
int n = in.nextInt();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.