从java中的文件中读取

时间:2015-03-01 14:15:02

标签: java file-io

我正在使用此代码从文件中读取:

BufferedReader in = new BufferedReader(new FileReader("example.txt"));


      String line;
 while((line = in.readLine()) != null)
{
         String k = line;
        System.out.println(k);
 }
in.close();

这完全正常。但是我的文本文件包含" 1。你好2.再见3. Seeya" ..我如何修改我的代码,以便" 1。你好"存储在一个变量中。" 2。再见"存储在不同的变量..等等  提前谢谢!

2 个答案:

答案 0 :(得分:1)

如果它是一行,您可以使用以下内容:

s.split("(?<=\\w)\\s"));

由于split接受正则表达式,您可以根据前面有字符的空格进行拆分。

快速举例:

public static void main(String[] args) {
    String s = "1. Hello 2. Bye 3. Seeya";
    System.out.println(Arrays.deepToString(s.split("(?<=\\w)\\s")));
}

输出:

[1. Hello, 2. Bye, 3. Seeya]

如果您引用了多行,则只需循环播放这些行,然后将每一行添加到ArrayList

如果您的输入可以在每个数字项目符号中包含一个或多个字符串,则应使用\\s(?=\\d+[.])这是一个空格后跟数字和点 - 感谢@pshemo

答案 1 :(得分:0)

您可以这样做..

由于数据是分开的,因此非常简单。您只需使用arrayList即可接收数据。

ArrayList可以&#34;成长&#34;并且&#34;收缩&#34;如所须。与具有固定大小的数组不同。

 public static void main(String[] args) throws FileNotFoundException
 {
      List<String> record = new ArrayList<String>();     //Use arraylist to store data
      Scanner fScn = new Scanner(new File(“Data.txt”));
      String data;

      while( fScn.hasNextLine() ){
           data = fScn.nextLine();
           record.add(data);   //Add line of text to the array list
      }
      fScn.close();
 }

要从arraylist中检索记录,您只需使用for循环或for-each循环。

for(int x=0; x<record.size(); x++)
    System.out.println(record.get(x));  

//Get specific record with .get(x) where x is the element id starting from 0. 
//0 means the first element in your arraylist.