我知道这已经被问过很多次了,但我在这里遇到了问题。我希望能够逐行读取自定义文件类型,以便执行保存和加载等操作。谁能写一小段代码来告诉我如何做到这一点?
这是我想阅读的方式:
//Here is where the code to get the file should be
while((String text = reader.readLine()) != null)
{
if (text.startsWith("add"))
//ect
}
Jar 文件是 ZIP 文件,其中包含所有 java 编译的类文件和其他材料。为了读取 JAR 文件中的文件,您必须能够读取 zip 文件。这里有一个例子:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ReadZip {
public static void main(String args[]) {
try {
ZipFile zf = new ZipFile("ReadZip.zip");
Enumeration entries = zf.entries();
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
while (entries.hasMoreElements()) {
ZipEntry ze = (ZipEntry) entries.nextElement();
System.out.println("Read " + ze.getName() + "?");
String inputLine = input.readLine(); // your code here
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
来自:http ://www.java2s.com/Code/Java/File-Input-Output/ReadingtheContentsofaZIPFile.htm
假设我们正在谈论的 jar 是您的应用程序或您的应用程序的依赖项之一,这应该可以工作
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(path)));
path - jar 中文件的路径,例如“/test/test.txt”
要从 jar 资源中打开文件,请参阅:Class#getResourceAsStream。
读取文本文件的代码示例:
try {
InputStream in = getClass().getResourceAsStream("resource name"); // get binary stream to resource
// InputStream in = new FileInputStream("filePath"); //in case file loaded from the FileSystem
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null)
{
if (line.startsWith("add")) {
// e.t.c.
}
}
}
catch (IOException e) {
//process exception or throw up
}
使用Guava从资源加载文件更容易:
URL url = Resources.getResource(resourceName);
List<String> text = Resources.readLines(url, Charsets.UTF_8);