java i/o 读取多行文件并存储为arraylist [英] java i/o read in multi line file and store as arraylist

查看:32
本文介绍了java i/o 读取多行文件并存储为arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读入一个简单的文本文件并将其保存为一个 ArrayList.文件看起来像这样

I want to read in a simple text file and save it as an ArrayList. The file looks like so

0.2253 
0.808 
0.132 
0.341 

4.18546
8.65418
1.45535
0.341

and so on...

它们将始终为四行,并且始终以空格分隔.不知何故,我想用它作为断点来开始新的数组,并以第一个新数字作为索引零.

They will always be four lines and they will always be delimited by a blank space. Somehow I'd like to use that as the break point to begin the new array and pick back up with the first new number as index zero.

数字必须存储为字符串.

The numbers must be stored as strings.

我想将此数据分配给一个 ArrayList 使得

I want to assign this data to an ArrayList such that

[0][0] = 0.2253
[0][1] = 0.808
[0][2] = 0.132
[0][3] = 0.341

[1][0] = 4.18546
[1][1] = 8.65418
[1][2] = 1.45535
[1][3] = 0.341

如何使用 java i/o 的结构来做到这一点?

how can I do this using the structures of java i/o?

java io 数组列表

java io arraylist

到目前为止我有这个..

So far I have this..

    //array list data struc
    ArrayList<String> array_list = new ArrayList<String>();

    String component_doc = "/home/joao/document.txt"

    Scanner inFile = null;
    try 
    {
        inFile = new Scanner(new File(component_doc));
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }

    while(inFile.hasNextLine())
    {
        array_list.add(inFile.nextLine());
    }

推荐答案

这是一种读取这些行并将它们放入数组列表的方法.

This is a way to read in those lines and put them in an array list.

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

protected static ArrayList<String> yourArrayList = new ArrayList<String>();
String fileName = "C:\\Users\\myComputer\\Desktop\\test_file.txt";
    try
    {
        List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
        for (int i = 0; i < lines.size(); i++)
        {
            yourArrayList.add(lines.get(i).toString());
        }
    }catch(IOException io)
    {
        io.printStackTrace();
    }

这篇关于java i/o 读取多行文件并存储为arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆