Java的:读入文件到一个数组 [英] Java: Reading a file into an array

查看:171
本文介绍了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.

问题是,我每次都遇到一个例外。显然,它不能找到它(我相信它的拼写正确)。当寻找到code范例,它没有指定文件的完整文件路径,只有文件本身的名称。我怎么会去这样做,如果它的必要吗?

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类的,就是它的目的,它是如何corelate阅读输入?

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

推荐答案

下面是一些例子code,以帮助您开始:

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()]);
    }
}

和一个例子单元测试:

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天全站免登陆