java读取文件方法大全
下文笔者讲述使用java代码读取文件的方法大全,如下所示
实现思路: 使用BufferedReader, Scanner, StreamTokenizer, DataInputStream, SequenceInputStream, FileChannel 这些类即可实现读取文件的目的例:
使用InputStream读取
private String readFromInputStream(InputStream inputStream) throws IOException { StringBuilder resultStringBuilder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = br.readLine()) != null) { resultStringBuilder.append(line).append("\n"); } } return resultStringBuilder.toString(); }
从Classpath路径下读取文件
从src/main/resources读取文件fileTest.txt @Test public void test() throws IOException { String expectedData = "Hello,World!"; Class<ReadFileTest> clazz = ReadFileTest.class; InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); String data = readFromInputStream(inputStream); Assert.assertThat(data, containsString(expectedData)); }
使用commons-io库
引入相应的依赖 <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.4</version> </dependency> @Test public void useCommonIO() throws IOException { ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("fileTest.txt").getFile()); String data = FileUtils.readFileToString(file, "UTF-8"); } @Test public void useCommonIO2() throws IOException { String expectedData = "Hello,World!"; FileInputStream fis = new FileInputStream("src/test/resources/fileTest.txt"); String data = IOUtils.toString(fis, "UTF-8"); assertEquals(expectedData, data.trim()); }
BufferedReader
@Test public void bufferedReader() throws IOException { String file ="src/test/resources/fileTest.txt"; BufferedReader reader = new BufferedReader(new FileReader(file)); String currentLine = reader.readLine(); reader.close(); }
Java NIO读取文件
@Test public void readSmallFile() throws IOException { Path path = Paths.get("src/test/resources/fileTest.txt"); String read = Files.readAllLines(path).get(0); }
读取大文件
@Test public void readLargeFile() throws IOException { Path path = Paths.get("src/test/resources/fileTest.txt"); BufferedReader reader = Files.newBufferedReader(path); String line = reader.readLine(); }
Files.lines
在JDK8中 Files类增加了lines方法 这个方法将返回Stream<String> 跟文件操作一样 Stream需要显式调用的close()
Scanner
下面我们将使用Scanner读取文件,使用逗号(,)作为定界符(delimiter)。 @Test public void whenReadWithScanner_thenCorrect() throws IOException { String file = "src/test/resources/fileTest.txt"; Scanner scanner = new Scanner(new File(file)); scanner.useDelimiter(","); System.out.Println(scanner.hasNext()); scanner.close(); } Scanner默认的定界符是空格
StreamTokenizer
tokenizer会指出下一个token的类型,String或Number。 tokenizer.nval - 如果类型为Number时,读取该字段 tokenizer.sval - 如果类型为String时,读取该字段 @Test public void readWithTokenize() throws IOException { String file = "src/test/resources/fileTestTokenizer.txt"; FileReader reader = new FileReader(file); StreamTokenizer tokenizer = new StreamTokenizer(reader); // 1 tokenizer.nextToken(); assertEquals(StreamTokenizer.TT_WORD, tokenizer.ttype); assertEquals("Hello", tokenizer.sval); // 2 tokenizer.nextToken(); assertEquals(StreamTokenizer.TT_NUMBER, tokenizer.ttype); assertEquals(1, tokenizer.nval, 0.0000001); // 3 tokenizer.nextToken(); assertEquals(StreamTokenizer.TT_EOF, tokenizer.ttype); reader.close(); }
DataInputStream
使用DataInputStream @Test public void whenReadWithDataInputStream() throws IOException { String file ="src/test/resources/fileTest.txt"; String result = null; DataInputStream reader = new DataInputStream(new FileInputStream(file)); int nBytesToRead = reader.available(); if(nBytesToRead > 0) { byte[] bytes = new byte[nBytesToRead]; reader.read(bytes); result = new String(bytes); } }
FileChannel
注意事项: FileChannel运行速度会超过standard IO @Test public void whenReadWithFileChannel() throws IOException { String expected_value = "Hello,World!"; String file = "src/test/resources/fileTest.txt"; RandomAccessFile reader = new RandomAccessFile(file, "r"); FileChannel channel = reader.getChannel(); int bufferSize = 1024; if (bufferSize > channel.size()) { bufferSize = (int) channel.size(); } ByteBuffer buff = ByteBuffer.allocate(bufferSize); channel.read(buff); buff.flip(); assertEquals(expected_value, new String(buff.array())); channel.close(); reader.close(); }
读取utf-8编码的文件
@Test public void whenReadUTFEncodedFile() throws IOException { String file = "src/test/resources/fileTestUtf8.txt"; BufferedReader reader = new BufferedReader (new InputStreamReader(new FileInputStream(file), "UTF-8")); String currentLine = reader.readLine(); reader.close(); }
从URL读取数据
@Test public void readFromURL() throws IOException { URL urlObject = new URL("http://www.java265.com"); URLConnection urlConnection = urlObject.openConnection(); InputStream inputStream = urlConnection.getInputStream(); String data = readFromInputStream(inputStream); }
从jar包中读取文件
@Test public void readFromJar() throws IOException { Class clazz = Test.class; InputStream inputStream = clazz.getResourceAsStream("/test.txt"); String data = readFromInputStream(inputStream); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。