簡體   English   中英

Java /從.txt文件讀取

[英]Java/ read from .txt file

我有.txt文件,並且我想從中讀取到char數組。

我有問題,在.txt文件中,我有:

1  a

3  b

2  c

這意味着a [1] ='a',a [3] ='b',a [2] ='c'。

在讀取文件時,如何忽略空格並考慮換行? 謝謝

我建議您為此使用Map ,因為它更適合此類問題。

public static void main(String[] args) {

    Scanner s = new Scanner("1 a 3 b 2 c"); // or new File(...)

    TreeMap<Integer, Character> map = new TreeMap<Integer, Character>();

    while (s.hasNextInt())
        map.put(s.nextInt(), s.next().charAt(0));
}

如果要將TreeMap轉換為char[] ,可以執行以下操作:

char[] a = new char[map.lastKey() + 1];

for (Entry<Integer, Character> entry : map.entrySet())
    a[entry.getKey()] = entry.getValue();

筆記:

  • 此解決方案不適用於負索引
  • 如果不止一個,則僅采用“第一個”字符

使用Scanner可能是最簡單的方法。

ArrayList<String> a = new ArrayList<String>();
Scanner s = new Scanner(yourFile);
while(s.hasNextInt()) {
    int i = s.nextInt();
    String n = s.next();
    a.add(n);
}

當然,這大膽地假設正確的輸入。 你應該更加偏執。 如果需要專門處理每一行,則可以使用hasNextLine()nextLine() ,然后使用String類中的split()拆分行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM