在java中读取文件

在java中读取文件,java,file-io,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.

我正在使用以下代码读取文件:

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.再见”。。如何修改代码,使“1.Hello”存储在变量中。。“2.Bye”存储在不同的变量中。。等等
提前谢谢

如果是一行,可以使用以下命令:

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

[1. Hello, 2. Bye, 3. Seeya]
如果要引用多行,只需在这些行上循环,并将每一行添加到
ArrayList


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

这就是您可以做到的方法。

由于数据在单独的行中,因此非常直接。您只需使用
arrayList
即可接收数据

ArrayList可以根据需要“增长”和“收缩”。与具有固定大小的数组不同

 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();
 }
publicstaticvoidmain(字符串[]args)抛出FileNotFoundException
{
列表记录=新建ArrayList();//使用ArrayList存储数据
Scanner fScn=新扫描仪(新文件(“Data.txt”);
字符串数据;
而(fScn.hasNextLine()){
data=fScn.nextLine();
record.add(data);//将文本行添加到数组列表中
}
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.

用于(int x=0;XY您不能动态创建变量。请使用数组。如何创建变量完全取决于您的文件格式。您需要指定文件中文本的格式。是否确认始终存在数字?是否始终每个变量的内容都以数字开头?文件中是否有空行?文本
1.Hello 2.再见3.Seeya
在一行中,或者每个部分在单独的行中?它们在单独的行中,使用类似于ArrayList的列表实现。它类似于ArrayList,但与此不同的是,它可以调整大小,以便您可以添加新元素,而不必担心超出范围。万一数据可能是
1.你好,世界2.再见3.Seeya我更喜欢
\\s(?=\\d+[.])
以避免在
hello world
之间拆分。基于此,看起来所有这些值实际上都在单独的行中,所以我们不需要拆分它们,只需将它们存储在列表中的某个位置即可。
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.