2011-11-06 15 views
1

我正在創建一個應用程序,在其中列出教師和他們在我的學校所做的所有事情。我有3個文件,一個教師類,它是一個可以容納7個字符串變量的對象,一個TeacherList類,在這裏我接收.txt文件並從中提取數據以形成教師。這是我的問題在哪裏,我應該在哪裏放置文件?繼承人TeacherList代碼:如何在Android應用程序中訪問簡單的txt文件?

package com.mthebron.mthapp; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class TeacherList { 
public static Teacher[] MakeList() throws FileNotFoundException{ 
    Teacher[] teachers=new Teacher[71]; 
    File list=new File("C:/Users/Gareth/Desktop/TeacherInformation.txt"); 
    Scanner iScanner=new Scanner(list); 
    StringBuilder teachersBuilder=new StringBuilder(); 
    while(iScanner.hasNext()) { 
     teachersBuilder.append(iScanner.nextLine()); 
     teachersBuilder.append("\n"); 
    } 
    String fullList=teachersBuilder.toString(); 
    String[] seperatedList=fullList.split("'"); 
    String[] blah=seperatedList[0].split("\n"); 
    String temp=blah[0].substring(3, 9);  
    String name=temp; 
    String department=blah[1]; 
    String planning=blah[2]; 
    String club=blah[3]; 
    String sport=null; 
    String email=blah[5]; 
    String website=null; 
    teachers[0]=new Teacher(name, department, planning, club, sport, email, website); 
    System.out.println(teachers[0].getSportsCoached()); 
    for (int i = 1; i < seperatedList.length; i++) { 
     blah=seperatedList[i].split("\n"); 
     name=blah[1]; 
     department=blah[2]; 
     if (blah[3].equals("null")) { 
      planning=null; 
     }else planning=blah[3]; 
     if (blah[4].equals("null")) { 
      sport=null; 
     }else sport=blah[4]; 
     if (blah[5].equals("null")) { 
      club=null; 
     }else club=blah[5]; 
     if (blah[6].equals("null")) { 
      email=null; 
     }else email=blah[6]; 
     if (blah[7].equals("null")) { 
      website=null; 
     }else website=blah[7]; 
     teachers[i]=new Teacher(name, department, planning, sport, club, email, website); 
    } 
    return teachers; 
} 

我應該在哪裏放置該文件,並且它仍然能夠作爲文件對象工作?

回答

1

如果你不知道放在哪裏的文件,你可以簡單地說

​​

,它會保存在本地,您可以訪問它以同樣的方式

+0

那麼在哪裏將「本地」,像在Android項目的文件夾? – werdho

0

它是一個固定的文件或者是你添加到它?如果修復,則放入資產文件夾。像......

Scanner iScanner=new Scanner(getAssets().open("TeacherInformation.txt")); 
+0

當我添加這條線,我得到一個錯誤,說getAssets不是一個方法 – werdho

+0

該文件也是固定的,我將它添加到資產文件夾 – werdho

+0

你需要一個「上下文」。我假設你是從你的活動直接打電話。看到這裏:http://developer.android.com/reference/android/content/Context.html#getAssets() –

相關問題