使用工具类读取文件

package com.kenny.file;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by kenny.dong on 2018/6/6.
 */
public class FileUtilTest {
    /**
     * 测试读取一个外部文件并依次按行读取
     * 依赖jar包:commons-io:commons-io:
     * compile group: 'commons-io', name: 'commons-io', version: '2.6'
     * 类似的也有compile group: 'springframework', name: 'spring-core', version: '1.2.6'下面的
     * StreamUtils和FileCopyUtils,可以参考
     * @throws IOException
     */
    @Test
    public void testReadFileLines() throws IOException {
        File file = new File("D://file.txt");
        FileInputStream inputStream = FileUtils.openInputStream(file);
        try {
            LineIterator it = IOUtils.lineIterator(inputStream, "GBK");
            while (it.hasNext()) {
                String line = it.nextLine();
                System.out.println(line);
            }
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }
}

 

你可能感兴趣的:(Java)