Java:将文件读入数组 [英] Java: Reading a file into an array

查看:45
本文介绍了Java:将文件读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件(称为number.txt"),我想将它读入 Java 中的数组.我该如何继续并做到这一点?这是一个简单的一维"文件,包含 100 个数字.

I have a file (called "number.txt") which I want to read to an array in Java. How exactly do I go ahead and do this? It is a straight-forward "1-dimensional" file, containing 100 numbers.

问题是我每次都会遇到异常.显然它找不到它(我确定它的拼写正确).在查看代码示例时,它没有指定文件的整个文件路径,只指定文件本身的名称.如果有必要,我会怎么做?

The problem is that I get an exception every time. Apparently it can't find it (I am sure its spelled correctly). When looking through code examples, it doesn't specify the file's entire file path, only the name of the file itself. How would I go about doing that if its necessary?

此外,在读取文件时,数组会自动包含文件的所有行,还是必须创建一个循环将每一行复制到相应的下标 i?

Also, when reading the file, will the array automatically contain all the lines of the file, or will I have to make a loop which which copies every line to corresponding subscript i?

我听说过 BufferedReader 类,它的用途是什么,以及它如何与读取输入相关联?

I've heard of BufferedReader class, what it's purpose, and how does it corelate to reading input?

推荐答案

以下是一些示例代码,可帮助您入门:

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

以及一个示例单元测试:

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

希望这会有所帮助.

这篇关于Java:将文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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