[英]Java reading text file with delimiter and pushing into an array
我正在讀取一個在元素之間有定界符的文件。 我正在嘗試將每個元素放入數組的新索引中。 這似乎無法正常工作,一切似乎都結束於數組的一個索引上。 下面是一個示例文本文件和我的代碼。
文本文件
%User %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel%James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel %James %Fields %Will Smith %sBel
碼
final InputStream i = getResources().openRawResource(R.raw.users);
final Scanner s = new Scanner(i);
try
{
while (s.hasNextLine())
{
String d = s.nextLine();
String test;
test = values[1];
userTextArea.append(test);
test = "";
}
}
final InputStream i = getResources().openRawResource(R.raw.users);
final Scanner s = new Scanner(i);
try
{
while (s.hasNextLine())
{
String d = s.nextLine();
StringTokenizer st = new StringTokenizer(d,"%");
String[] myStringArray = new String[st.countTokens()]
int index = 0;
while(st.hasMoreTokens()) {
myStringArray[index] = st.nextElement();
index ++;
}
}
} catch (Exception e) {
....
}
您必須使用分割功能。
String tmp = "%hallo %world";
String [] strArray = tmp.split("%");
System.out.print(strArray[0]); //prints hallo
數組是一個容器對象,其中包含固定數量的存儲在唯一索引(位置)中的值。
原因
一切似乎都以數組的一個索引結尾
這樣做有兩個原因:
您正在讀取的文件沒有換行符。 因此,當您調用nextLine()時,它將把所有文件內容分配給變量“ d ”。
String d = s.nextLine();
為了清楚起見,在您的程序中,“ d ”保存您的整個文本文件。
即使它確實包含換行符,您仍然不會將任何內容讀入數組。 將字符串分配給變量“ d ”后。 您對此沒有做任何事情。
意見建議
一種方法是:
逐行讀取文件,然后使用String split()函數拆分元素,此函數返回一個數組,因此您需要將其分配給String []數組變量。 省略while循環,因為您只需要讀取一行。 之后,遍歷字符串數組並將值附加到文本區域:
String d = s.nextLine(); String[] values = d.split("%"); for(String value: values) { userTextArea.append(value.trim()); }
追加時,不要忘記修剪字符串,因為文件中的元素之間包含空格。 字符串trim()函數將刪除這些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.