从jar文件运行java应用程序时java.io.FileNotFoundException
嗨,我正在从jar文件运行java应用程序。类似下面的从jar文件运行java应用程序时java.io.FileNotFoundException,java,filenotfoundexception,Java,Filenotfoundexception,嗨,我正在从jar文件运行java应用程序。类似下面的java-cp test.jar com.test.TestMain。在java应用程序中,我正在读取csv文件。这是抛出下面的异常 java.io.FileNotFoundException: file:\C:\Users\harinath.BBI0\Desktop\test.jar!\us_postal_codes.csv (The filename, directory name, or volume label syntax is i
java-cp test.jar com.test.TestMain
。在java应用程序中,我正在读取csv文件。这是抛出下面的异常
java.io.FileNotFoundException: file:\C:\Users\harinath.BBI0\Desktop\test.jar!\us_postal_codes.csv (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at com.test.TestMain.run(TestMain.java:63)
at com.test.TestMain.main(TestMain.java:43)
*csv file is located in src/main/resources folder.
谢谢。根据下面的堆栈跟踪,我们可以看到扫描仪找不到文件:
at java.util.Scanner.<init>(Scanner.java:656)
at com.test.TestMain.run(TestMain.java:63)
test.jar\us_postal_codes.csv(文件名、目录名或卷
标签语法不正确)
建议使用
System.getProperty("user.dir") // to get the current directory, if the resource is in the project folder
及
您应该使用getResourceAsStream。例如:
public void test3Columns() throws IOException
{
InputStream is = getClass().getResourceAsStream("3Columns.csv");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
CSVLineTokenizer tok = new CSVLineTokenizer(line);
assertEquals("Should be three columns in each row",3,tok.countTokens());
}
br.close();
isr.close();
is.close();
}
ClassLoader.getResource方法不用于搜索.jar存档中的文件。您可以共享更多TestMain.java中的代码吗?那么com.test.TestMain.run(TestMain.java:63)和com.test.TestMain.main(TestMain.java:43)中的这两行代码是什么在您的类中?将
src/main/resources
放在classpathcode updated@nullpointer中。你能检查一下吗。建议使用System.getProperty(“user.dir”)
查找jar文件中的当前工作目录CSV文件。从根本上说。但还是被处决了java.lang.NullPointerException位于java.io.Reader.(Reader.java:78)位于java.io.InputStreamReader.(InputStreamReader.java:72)位于java.util.Scanner.(Scanner.java:608)
HI它工作正常,我只是像这样将“/”放在文件名上。“/us\u邮政编码.csv”。谢谢@tamas rev谢谢它的工作。小零钱getResourceAsStream(“/us\u postal\u codes.csv”)@Harinath:我的错,improved@Harinath:如果这解决了您的问题,请选择它作为答案
System.getProperty("user.dir") // to get the current directory, if the resource is in the project folder
getResourceAsStream("/us_postal_codes.csv") // if its inside a jar
public void test3Columns() throws IOException
{
InputStream is = getClass().getResourceAsStream("3Columns.csv");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null)
{
CSVLineTokenizer tok = new CSVLineTokenizer(line);
assertEquals("Should be three columns in each row",3,tok.countTokens());
}
br.close();
isr.close();
is.close();
}