有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java布尔方法中导入文本文件

我正在编写一个布尔方法,如果文本文件导入成功,我需要返回True。我还需要能够单独访问每行的每个字符串和int。因此,如果文本文件包含以下内容:

贝克街东北1号

我想返回真实的情况,并且能够分别访问贝克街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);


} 

共 (1) 个答案

  1. # 1 楼答案

    看看这个例子

     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;
    
       }
    }
    

    这是虚拟街道。我使用的txt文件

     1 North East Baker St
     890 North Sonoita Ave
     180 South Swan Rd