我正在编写一个布尔方法,如果成功导入文本文件,我需要在其中返回True。我还需要能够单独访问每行的每个String和int。因此,如果文本文件包含以下内容:
东北贝克街1号
我想返回True,并能够单独访问1号、北部和东贝克街。文本文件也是多行的,所以我不知道这是否会改变什么。谢谢
这就是我到目前为止所拥有的。我无法编译它,也不知道我是否走上了正确的道路。
String nameFile = "";
public boolean readFile(String filename)
{
nameFile = filename;
FileReader file = new FileReader(nameFile);
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while (line != null)
{
text += line;
line = reader.readLine();
}
System.out.println(text);
}
查看此示例。
public class StreetHandling {
List<Integer> number;
List<String> firstWord;
List<String> rest;
public StreetHandling() {
number = new ArrayList();
firstWord = new ArrayList();
rest = new ArrayList();
}
public static void main(String[] args) {
StreetHandling sh = new StreetHandling();
System.out.println("Read file : "+sh.finishReadFile("streets.txt"));
//you can use the lists anyway you want from here
}
public boolean finishReadFile(String fname) {
boolean finishRead = false;
try {
FileReader file = new FileReader(fname);
BufferedReader br = new BufferedReader(file);
String s = "";
String arr[] = null;
while (br.ready()) {
s = br.readLine().trim();
arr = s.split(" ");
number.add(Integer.parseInt(arr[0]));
firstWord.add(arr[1]);
rest.add(s.substring(arr[0].length() + arr[1].length() + 1));
}
finishRead = true;
} catch (Exception e) {
System.out.println(e);
}
return finishRead;
}
}
这是我使用的伪streets.txt文件
1 North East Baker St
890 North Sonoita Ave
180 South Swan Rd