假设有如下目录结构的代码,现在想要获取test.txt文件中的内容,test.txt中的内容为hello world。
问题代码如下:
package mvnDemo;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class MvnDemo {
public static void main(String[] args) throws IOException {
System.out.println(StringUtils.upperCase("hello mvn"));
String path = MvnDemo.class.getClassLoader().getResource("test.txt").getPath();
String testString = FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);
System.out.println(testString);
}
}
结果如下:
hello world
但打成jar包执行后,却会报错如下:
D:\>java -jar D:\testDemo-1.0-SNAPSHOT.jar
Exception in thread "main" java.io.FileNotFoundException: file:\D:\testDemo-1.0-SNAPSHOT.jar!\test.txt (文件名、目录名或卷标语法不正确。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:2388)
at org.apache.commons.io.FileUtils.readFileToString(FileUtils.java:2506)
at mvnDemo.MvnDemo.main(MvnDemo.java:15)
正确代码如下:
package mvnDemo;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class MvnDemo {
public static void main(String[] args) throws IOException {
System.out.println(StringUtils.upperCase("hello mvn"));
InputStream resourceAsStream = MvnDemo.class.getClassLoader().getResourceAsStream("test.txt");
List<String> stringList = IOUtils.readLines(resourceAsStream, StandardCharsets.UTF_8);
String testString = StringUtils.join(stringList, "");
System.out.println(testString);
}
}
这种方式处理,无论在idea中执行,还是打包执行,都能获取预期的结果。