在Java里如何读取文件 在java里如何读取文件数据
bigegpt 2024-10-12 06:12 8 浏览
1.概述
在这篇文章里, 我们将探索不同的方式从文件中读取数据。
首先, 学习通过标准的的Java类,从classpath、URL或者Jar中加载文件。
然后,学习通用BufferedReader, Scanner, StreamTokenizer, DataInputStream, SequenceInputStream, FileChannel读取文件内容。也会讨论如何读取UTF-8编码的文件。
最后,学习Java7和Java8中新的加载和读取文件的技术。
2.准备
2.1 输入文件
这篇文章的很多示例,从名为fileTest.txt的文件读取文本内容,文件包含
Hello,World!
有少量示例, 我们会读取不同的文件, 示例中会有说明。
2.2 辅助方法
很多示例都会用到共用的方法readFromInputStream, 该方法将InputStream转化String
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();
}
3.从Classpath读取文件
3.1 使用标准Java
从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));
}
在上面的代码中,我们通过当前类的getResourceAsStream方法加载文件,入参是绝对路径。
ClassLoader中相同的方法也可以使用。
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt");
String data = readFromInputStream(inputStream);
这两种方法的主要区别是, 当前类的ClassLoader的getResourceAsStream方法,入参路径是从classpath开始。
而类实例的入参是相对于包路径,但路径开始使用'/'符号, 也是绝对路径。
特别要注意的是, 文件打开读取完数据后, 始终需要关闭
inputStream.close();
3.2 使用commons-io库
另一个比较常用的方法是使用commons-io包里的FileUtils.readFileToString方法。
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
@Test
public void useCommonIO() throws IOException {
String expectedData = "Hello,World!";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileTest.txt").getFile());
String data = FileUtils.readFileToString(file, "UTF-8");
assertEquals(expectedData, data.trim());
}
该方法入参是File对象。这个工具类的优点是不用编码InputStream实例的相关代码。
这个库还提供了IOUtils类。
@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());
}
4.BufferedReader
@Test
public void bufferedReader() throws IOException {
String expected_value = "Hello,World!";
String file ="src/test/resources/fileTest.txt";
BufferedReader reader = new BufferedReader(new FileReader(file));
String currentLine = reader.readLine();
reader.close();
assertEquals(expected_value, currentLine);
}
当读取结束的时候, reader.readLine()会返回null
5.Java NIO
NIO是在JDK7中添加。
5.1读取小文件
首先看一下关于Files.readAllLines的示例
@Test
public void readSmallFile() throws IOException {
String expected_value = "Hello,World!";
Path path = Paths.get("src/test/resources/fileTest.txt");
String read = Files.readAllLines(path).get(0);
assertEquals(expected_value, read);
}
入参Path对象,Path可以认为是java.io.File的升级版本,提供一些额外的功能。
如果读取的是二进制文件,可以使用Files.readAllBytes()方法
5.2读取大文件
如果想要读取大文件, 我们可以使用Files类和BufferedReader类。
@Test
public void readLargeFile() throws IOException {
String expected_value = "Hello,World!";
Path path = Paths.get("src/test/resources/fileTest.txt");
BufferedReader reader = Files.newBufferedReader(path);
String line = reader.readLine();
assertEquals(expected_value, line);
}
5.3Files.lines
在JDK8中,Files类增加了lines方法,这个方法将返回Stream<String>。跟文件操作一样,Stream需要显式调用的close()。Files API提供了很多简单读取文件的方法。
6.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(",");
assertTrue(scanner.hasNext());
assertEquals("Hello", scanner.next());
assertEquals("World!", scanner.next());
scanner.close();
}
Scanner默认的定界符是空格。它适用于从控制台读取输入或者内容有固定定界符的内容时。
7.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();
}
8.DataInputStream
如果要读取二进制文件或者原生数据,可以使用DataInputStream
@Test
public void whenReadWithDataInputStream() throws IOException {
String expectedValue = "Hello,World!";
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);
}
assertEquals(expectedValue, result);
}
9.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();
}
10.读取utf-8编码的文件
@Test
public void whenReadUTFEncodedFile()
throws IOException {
String expected_value = "你好,世界!";
String file = "src/test/resources/fileTestUtf8.txt";
BufferedReader reader = new BufferedReader
(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String currentLine = reader.readLine();
reader.close();
assertEquals(expected_value, currentLine);
}
11.从URL读取数据
@Test
public void readFromURL() throws IOException {
URL urlObject = new URL("https://www.baidu.com");
URLConnection urlConnection = urlObject.openConnection();
InputStream inputStream = urlConnection.getInputStream();
String data = readFromInputStream(inputStream);
}
12.从jar包中读取文件
我们的目标是读取junit-4.12.jar包中的LICENSE-junit.txt文件。clazz只需要这个Jar中的类就行。
@Test
public void readFromJar() throws IOException {
String expectedData = "Eclipse Public License";
Class clazz = Test.class;
InputStream inputStream = clazz.getResourceAsStream("/LICENSE-junit.txt");
String data = readFromInputStream(inputStream);
Assert.assertThat(data, containsString(expectedData));
}
相关推荐
- Go语言泛型-泛型约束与实践(go1.7泛型)
-
来源:械说在Go语言中,Go泛型-泛型约束与实践部分主要探讨如何定义和使用泛型约束(Constraints),以及如何在实际开发中利用泛型进行更灵活的编程。以下是详细内容:一、什么是泛型约束?**泛型...
- golang总结(golang实战教程)
-
基础部分Go语言有哪些优势?1简单易学:语法简洁,减少了代码的冗余。高效并发:内置强大的goroutine和channel,使并发编程更加高效且易于管理。内存管理:拥有自动垃圾回收机制,减少内...
- Go 官宣:新版 Protobuf API(go pro版本)
-
原文作者:JoeTsai,DamienNeil和HerbieOng原文链接:https://blog.golang.org/a-new-go-api-for-protocol-buffer...
- Golang开发的一些注意事项(一)(golang入门项目)
-
1.channel关闭后读的问题当channel关闭之后再去读取它,虽然不会引发panic,但会直接得到零值,而且ok的值为false。packagemainimport"...
- golang 托盘菜单应用及打开系统默认浏览器
-
之前看到一个应用,用go语言编写,说是某某程序的windows图形化客户端,体验一下发现只是一个托盘,然后托盘菜单的控制面板功能直接打开本地浏览器访问程序启动的webserver网页完成gui相关功...
- golang标准库每日一库之 io/ioutil
-
一、核心函数概览函数作用描述替代方案(Go1.16+)ioutil.ReadFile(filename)一次性读取整个文件内容(返回[]byte)os.ReadFileioutil.WriteFi...
- 文件类型更改器——GoLang 中的 CLI 工具
-
我是如何为一项琐碎的工作任务创建一个简单的工具的,你也可以上周我开始玩GoLang,它是一种由Google制作的类C编译语言,非常轻量和快速,事实上它经常在Techempower的基准测...
- Go (Golang) 中的 Channels 简介(golang channel长度和容量)
-
这篇文章重点介绍Channels(通道)在Go中的工作方式,以及如何在代码中使用它们。在Go中,Channels是一种编程结构,它允许我们在代码的不同部分之间移动数据,通常来自不同的goro...
- Golang引入泛型:Go将Interface「」替换为“Any”
-
现在Go将拥有泛型:Go将Interface{}替换为“Any”,这是一个类型别名:typeany=interface{}这会引入了泛型作好准备,实际上,带有泛型的Go1.18Beta...
- 一文带你看懂Golang最新特性(golang2.0特性)
-
作者:腾讯PCG代码委员会经过十余年的迭代,Go语言逐渐成为云计算时代主流的编程语言。下到云计算基础设施,上到微服务,越来越多的流行产品使用Go语言编写。可见其影响力已经非常强大。一、Go语言发展历史...
- Go 每日一库之 java 转 go 遇到 Apollo?让 agollo 来平滑迁移
-
以下文章来源于GoOfficialBlog,作者GoOfficialBlogIntroductionagollo是Apollo的Golang客户端Apollo(阿波罗)是携程框架部门研...
- Golang使用grpc详解(golang gcc)
-
gRPC是Google开源的一种高性能、跨语言的远程过程调用(RPC)框架,它使用ProtocolBuffers作为序列化工具,支持多种编程语言,如C++,Java,Python,Go等。gR...
- Etcd服务注册与发现封装实现--golang
-
服务注册register.gopackageregisterimport("fmt""time"etcd3"github.com/cor...
- Golang:将日志以Json格式输出到Kafka
-
在上一篇文章中我实现了一个支持Debug、Info、Error等多个级别的日志库,并将日志写到了磁盘文件中,代码比较简单,适合练手。有兴趣的可以通过这个链接前往:https://github.com/...
- 如何从 PHP 过渡到 Golang?(php转golang)
-
我是PHP开发者,转Go两个月了吧,记录一下使用Golang怎么一步步开发新项目。本着有坑填坑,有错改错的宗旨,从零开始,开始学习。因为我司没有专门的Golang大牛,所以我也只能一步步自己去...
- 一周热门
- 最近发表
- 标签列表
-
- mybatiscollection (79)
- mqtt服务器 (88)
- keyerror (78)
- c#map (65)
- xftp6 (83)
- bt搜索 (75)
- c#var (76)
- xcode-select (66)
- mysql授权 (74)
- 下载测试 (70)
- linuxlink (65)
- pythonwget (67)
- androidinclude (65)
- libcrypto.so (74)
- linux安装minio (74)
- ubuntuunzip (67)
- vscode使用技巧 (83)
- secure-file-priv (67)
- vue阻止冒泡 (67)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)