我怎样才能读取文本文件到一个数组? [英] How can I read a text file into an array?

查看:81
本文介绍了我怎样才能读取文本文件到一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我该怎么去读取文本文件到一个数组,文本文件将包含线沿线的东西:

I was wondering how I can go about reading a text file into an array, the text file would contain something along the lines of:

string:string:string
string:string:string
string:string:string
etc

(字符串:字符串:字符串是在一行)

(string:string:string being on a single line)

推荐答案

更新:

我想你可能需要阅读的文件到一个数组,但你不知道设置数组的大小。您可以使用的java.util.ArrayList 为,然后将其转换为一个数组。

I think you might want to read a file into an array but you don't know set the size of an array. You can use a java.util.ArrayList for that and then convert it to an array.

FileReader fin = new FileReader(fileName);
Scanner src = new Scanner(fin);
ArrayList<String> lines = new ArrayList<String>();
src.useDelimiter(":");

while (src.hasNext()) {
    lines.add(src.nextLine());
    // replace above line with array
}
String[] lineArray = new String[lines.size()];
lines.toArray(lineArray);

您可以使用 java.util.Scanner中的类,然后使用 useDelimiter 功能。

You can use the java.util.Scanner class and then use the useDelimiter function.

FileReader fin = new FileReader(fileName);
Scanner src = new Scanner(fin);

src.useDelimiter(":");

while (src.hasNext()) {
    System.out.println(src.next());
    // replace above line with array
}

这里

这篇关于我怎样才能读取文本文件到一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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