[英]How do I use BufferedReader to read lines from a txt file into an array
[英]How do I simply read a .txt file that I created and count its lines
我對 Android Studio 很陌生,但我有兩個問題。
因此,目前我正在使用一種方法從 .txt 文件中獲取行並將其轉換為 ArrayList。 我正在使用 FileReader 和 LineNumberReader。 當我運行該程序時,即使此代碼在 Eclipse 上工作,也會激活捕獲。
我的問題: 1. 我目前將 .txt 文件存儲在資產的原始文件夾中。 這是放置它的正確位置嗎? 2.我使用的位置是“\\res\\raw\\city.txt”,是不是我調用的文件有誤?
這是我的代碼(在 Android Studio 中)以獲得更多上下文:
//Method to take a file and convert into an ArrayList
private ArrayList<String> txtArray(String fileLoc) throws IOException {
int n = 22;
File file = new File(fileLoc);
//Counts how many lines are in the system
try {
FileReader fr = new FileReader(fileLoc);
LineNumberReader lr = new LineNumberReader(fr);
lr.skip(Long.MAX_VALUE);
n = lr.getLineNumber();
Toast errorToast3 = Toast.makeText(getActivity(), "the Number of lines is " + n, Toast.LENGTH_SHORT);
errorToast3.show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast errorToast5 = Toast.makeText(getActivity(), "Fuk " + n, Toast.LENGTH_SHORT);
errorToast5.show();
}
Toast errorToast3 = Toast.makeText(getActivity(), "Still ok here " + n, Toast.LENGTH_SHORT);
errorToast3.show();
//Takes lines from the text file and converts into Array List
Scanner kb = new Scanner(new File(fileLoc));
Toast errorToast7 = Toast.makeText(getActivity(), "Pls work " + n, Toast.LENGTH_SHORT);
errorToast7.show();
ArrayList<String> test = new ArrayList<String>();
for (int i = 0; i < n; i++) {
test.add(kb.nextLine());
//kb.next();
}
return test;
謝謝你的幫助!
/
開頭)。 試試res/raw/city.txt
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.