[英]Trouble reading from text file with IDs on each line
我有一個名為“ q.txt”的文本文件,我想從該文件中讀取,並根據ID(主鍵)選擇與之關聯的字符串。 例如0014,<Random string here>
到目前為止,我已經創建了一種獲取#### ID的方法。 現在,我需要瀏覽文件並找到相應的字符串,然后將其輸出到textview。
我遇到的問題是FileNotFoundException和IOException。 所以我應該在哪里放置文本文件,所以我不需要添加整個路徑(例如D:\\ Projects \\ ... \\ q.txt),而只需添加“ q.txt”?
以及如何遍歷文件以便可以選擇隨機問題?
如果使用數組,我還需要使它動態。
鑒於您的文件包含以下內容:
id,question
0001,Some Question?
....
0014,Foo Bar?
...
9999,Last question?
然后,您必須將文件的每一行解析為兩個單獨的字段。 一個用於存儲ID,另一個用於存儲問題。 您已經通過randomID()
方法獲得了隨機ID,因此在您的onClick()
方法中,調用randomID()
以獲取隨機ID,並將其傳遞給loadDatabase()
方法以在文件中搜索該隨機ID。 請注意,您的文件中必須存在隨機ID 。
找到隨機ID后,將問題設置為TextView
。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
String id = randomID();
loadDataBase(id);
}
public String randomID() {//generates an ID for the next question ####
String id;
int questionID;
int challenge;
Random ran = new Random();
int randomChallenge = ran.nextInt(5);
if (randomChallenge == 0) {
challenge = 2;
questionID = ran.nextInt(12);
} else {
challenge = 0;
questionID = ran.nextInt(103);
}
id = Integer.toString(challenge) + String.format("%03d", questionID);
return id;
}
public void loadDatabase(String id) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader("q.txt"));
while ((br.readLine()) != null) {
String lineParsed = br.readLine().split(',');
if(lineParsed[0] == id) {
someTextView.setText(lineParsed[1]);
}
}
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found: " e.getMessage());
} catch (IOException e) {
System.err.println("IOException: " e.getMessage());
}
}
試試這個:1.輸入文件的路徑。
String basePath = new File("").getAbsolutePath();//this will get the path of the class of your program.
try{
BufferedReader strReader = new BufferedReader(new FileReader(basePath+"\\nameOfYourFile.extension"));//this will find your file
}catch(FileNotFoundException | IOException e){
//e
}
2.如果您想隨機選擇以下幾行:
String str=null;
int rng=(int)(Math.random()*NumberOfTheLinesInYourFile);//generate a random number
for(int i =0; i<rng;i++){
str=strReader.readLine();//pick the line at rng variable;
}
System.out.println(srt);
輸出:文件的1行隨機
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.