用Java读取纯文本文件

彷佛有多种方法能够用Java读写文件数据。 java

我想从文件中读取ASCII数据。 有哪些可能的方法及其区别? spa


#1楼

对于大型文件,我编写的这段代码要快得多: code

public String readDoc(File f) {
    String text = "";
    int read, N = 1024 * 1024;
    char[] buffer = new char[N];

    try {
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);

        while(true) {
            read = br.read(buffer, 0, N);
            text += new String(buffer, 0, read);

            if(read < N) {
                break;
            }
        }
    } catch(Exception ex) {
        ex.printStackTrace();
    }

    return text;
}

#2楼

这是不使用外部库的另外一种方法: get

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public String readFile(String filename)
{
    String content = null;
    File file = new File(filename); // For example, foo.txt
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        char[] chars = new char[(int) file.length()];
        reader.read(chars);
        content = new String(chars);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(reader != null){
            reader.close();
        }
    }
    return content;
}

#3楼

可能不像使用缓冲I / O那样快,可是很是简洁: input

String content;
    try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
        content = scanner.next();
    }

\\Z模式告诉Scanner ,定界符为EOF。 it


#4楼

这是一个简单的解决方案: io

String content;

content = new String(Files.readAllBytes(Paths.get("sample.txt")));

#5楼

用Java从文件中读取数据的最简单方法是利用File类读取文件,并使用Scanner类读取文件内容。 import

public static void main(String args[])throws Exception
{
   File f = new File("input.txt");
   takeInputIn2DArray(f);
}

public static void takeInputIn2DArray(File f) throws Exception
{
    Scanner s = new Scanner(f);
    int a[][] = new int[20][20];
    for(int i=0; i<20; i++)
    {
        for(int j=0; j<20; j++)
        {
            a[i][j] = s.nextInt();
        }
    }
}

PS:不要忘记导入java.util。*; 以便扫描仪正常工做。 file

相关文章
相关标签/搜索