我是 Java 新手,我正在尝试使用此类返回 "test.csv" 的内容。这只在我使用本地文件的路径时才有效。
public class CSVtoArray2 {
public static final String filename = "C:\\eclipse\\workspace\\project\\src\\main\\webapp\\resources\\csv\\test.csv";
public String testMethod() throws IOException {
BufferedReader wr = null;
try {
wr = new BufferedReader(new FileReader(new File(filename)));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = wr.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
wr.close();
return stringBuffer.toString();
} finally {
wr.close();
}
}
}
当我改变
“C:\eclipse\workspace\project\src\main\webapp\resources\csv\test .csv" 到“/resources/csv/test.csv”,
此类返回 null。
这里有人可以帮忙吗?
谢谢!
更新:
解决方案:
将我的 CSV 文件复制到项目资源文件夹:
ClassLoader classLoader = getClass().getClassLoader();
File filename = new File(classLoader.getResource("csv/test.csv").getFile());
最佳答案
org.apache.commons.io.IOUtils.toString(CSVtoArray2.class.getResourceAsStream("/csv/test.csv"), Charset.forName("UTF-8")))
这很棘手,资源的根路径是什么。在 Eclipse 中,您可以将某些文件夹(例如 webapp/recource)标记为资源文件夹。当您构建 jar 文件时,资源文件夹内容将位于根目录中。因此,如果您的资源路径从/开始,则意味着jar的根目录(即资源文件夹的根目录)。
我不使用相对路径,所以你可以看看 open resource with relative path in java获取更多相关信息。
关于java - bufferedReader 只读取本地csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46345429/