2017-04-08 87 views
0

我只是試圖做一個鍛鍊,我要讀的test.txt叫在以下格式的特定文件的一行:爪哇 - 讀從一個文件包含文本和數字

Sampletest 4

我想要做的是我想將文本部分存儲在一個變量中,並將數字存儲在另一個變量中。我仍然是一名初學者,所以我不得不穀歌來找到一些至少可以工作的東西,這是迄今爲止我所得到的。

public static void main(String[] args) throws Exception{ 
    try { 
     FileReader fr = new FileReader("test.txt"); 
     BufferedReader br = new BufferedReader(fr); 

     String str; 
     while((str = br.readLine()) != null) { 
      System.out.println(str); 
     } 
     br.close(); 

    } catch(IOException e) { 
     System.out.println("File not found"); 
    } 
+0

創建一個列表''持有文本部分,而另一個變量'名單'持有另一個 – nachokk

回答

0

你只需要:

String[] parts = str.split(" "); 

和零件[0]是文本(sampletest) 及配件[1],這使得閱讀數4

+0

其實你的榜樣不起作用分裂接收一個正則表達式。你應該像'\\ s +'一樣傳遞 – nachokk

2

使用Scanner,你的文件比DIY方式更容易:

try (Scanner scanner = new Scanner(new FileInputStream("test.txt"));) { 
    while(scanner.hasNextLine()) { 
     String name = scanner.next(); 
     int number = scanner.nextInt(); 
     scanner.nextLine(); // clears newlines from the buffer 
     System.out.println(str + " and " + number); 
    } 
} catch(IOException e) { 
    System.out.println("File not found"); 
} 

請注意使用試用資源語法,當退出try時自動關閉掃描儀,因爲Scanner實現了Closeable,因此可用。

0

好像你正在閱讀的整個文件內容(從test.txt文件)一行行,所以你需要兩個獨立的List對象來存儲數字和非數字線,如下圖所示:

String str; 
List<Integer> numericValues = new ArrayList<>();//stores numeric lines 
List<String> nonNumericValues = new ArrayList<>();//stores non-numeric lines 
while((str = br.readLine()) != null) { 
    if(str.matches("\\d+")) {//check line is numeric 
     numericValues.add(str);//store to numericList 
    } else { 
      nonNumericValues.add(str);//store to nonNumericValues List 
    } 
} 
0

你可以使用java工具Files#lines()

然後你可以做這樣的事情。使用String#split()用正則表達式解析每一行,在這個例子中我使用逗號。

public static void main(String[] args) throws IOException { 
    try (Stream<String> lines = Files.lines(Paths.get("yourPath"))) { 
     lines.map(Representation::new).forEach(System.out::println); 
    }   
} 

static class Representation{ 
    final String stringPart; 
    final Integer intPart; 

    Representation(String line){ 
     String[] splitted = line.split(","); 
     this.stringPart = splitted[0]; 
     this.intPart = Integer.parseInt(splitted[1]); 
    } 
} 
0

如果您確定該格式始終是文件中的每一行。

String str; 
List<Integer> intvalues = new ArrayList<Integer>(); 
List<String> charvalues = new ArrayList<String>(); 
try{ 
    BufferedReader br = new BufferedReader(new FileReader("test.txt")); 
    while((str = br.readLine()) != null) { 
    String[] parts = str.split(" "); 
    charvalues.add(parts[0]); 
    intvalues.add(new Integer(parts[0])); 
} 
}catch(IOException ioer) { 
ioer.printStackTrace(); 
}