java.io.FileNotFoundException while running java app from jar file - java

Hi i am running java app from jar file. like following java -cp test.jar com.test.TestMain . in the java app i am reading csv file. which is throwing below exception.
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.
code causes to exception is
public static void main(String[] args) throws Exception {
TestMain trainerScraper = new TestMain();
trainerScraper.run();
}
private void run() throws JsonParseException, JsonMappingException, IOException{
String line = "";
String cvsSplitBy = ",";
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
System.out.println(csvFile);
URL url = classLoader.getResource("us_postal_codes.csv");
String fileName = url.getFile();
File file = new File(fileName);
try (Scanner scanner = new Scanner(file)) {
line = scanner.nextLine(); //header
while ((scanner.hasNextLine())) {
thanks.

test.jar!\us_postal_codes.csv (The filename, directory name, or volume
label syntax is incorrect)
Would suggest using
System.getProperty("user.dir") // to get the current directory, if the resource is in the project folder
and
getResourceAsStream("/us_postal_codes.csv") // if its inside a jar

Based on the stack trace below we can see that the Scanner cannot find the file:
at java.util.Scanner.<init>(Scanner.java:656)
at com.test.TestMain.run(TestMain.java:63)
By the way, where is the file? If it's in the jar, then you can use TestMain.class.getResourceAsStream() - Scanner has an InputStream constructor too:
InputStream iStream = TestMain.class.getResourceAsStream("/us_postal_codes.csv"); // this supposes the csv is in the root of the jar file
try (Scanner scanner = new Scanner(iStream)) {
//...
}
//...

You should use getResourceAsStream. This is example:
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 method is not used to search files in .jar archives.

Related

How to accept command line arguments for files

public static void main(String[] args) throws FileNotFoundException {
File inputFile = null;
File outputFile = null;
if (args.length > 0) {
String inputName = args[0];
String outputName = args[1];
inputFile = new File(inputName);
outputFile = new File(outputName);
}else{
Scanner input = new Scanner(System.in);
inputFile = new File(input.next());
outputFile = new File(input.next());
}
}
this is my code and it's supposed to check the command line arguments for the file name but if there are none it will let the user type the names in. but how do I get it to throw the file not found exception?? i appreciate any help
You're better off using java.nio.file.Path over the older File class. java.nio.file.Files has a lot of utility methods for Paths.
You could check if the file exists then throw your own FileNotFoundException:
Path path = Path.of(filename);
if (!Files.exists(path)) throw new FileNotFoundException(path.toString());
Alternatively you could generate a NoSuchFileException:
path.getFileSystem().provider().checkAccess(path);

Invalid File path even though I have checked it in java

I am using java.net.DatagramPacket to trans file. I have some code below
public void sendFile(InetAddress clientHost, int clientPort, String fileName) throws IOException {
String filePath = "e:\\uri\\" + fileName;
System.out.println(filePath);
FileInputStream inputFile = new FileInputStream(filePath);
}
I have a folder uri in and do create file.txt first. While debuging this, this is what shows up in console:
e:\uri\file.txt
java.io.FileNotFoundException: Invalid file path
at java.io.FileInputStream.<init>(FileInputStream.java:133)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at MyFileServerSocket.sendFile(MyFileServerSocket.java:19)
at FiletransServer.main(FiletransServer.java:22)
I found something more interesting that i can see the value of fileName in eclipse and it's strange.
There is extra quotation marks in there and the string printed in the console is normal. No idea why.
I suppose fileName you've passed into sendFile(...) has illegal characters. Please check it thoroughly and you should try hardcode filePath something like this and try once again:
public void sendFile(InetAddress clientHost, int clientPort, String fileName) throws IOException {
// Hardcode file.txt
String filePath = "e:\\uri\\file.txt";
// Print fileName surrounded with quoutes
System.out.printf("'%s'", fileName);
FileInputStream inputFile = new FileInputStream(filePath);
}

Read an existing text file in Java

I'm a Java Beginner and I'm trying to make a program of reading from an existing text file. I've tried my best, but it keep on saying "File Not Found!". I've copied my "Test.txt" to both the folders - src and bin of my package.
Kindly help me into this. I'll be very thankful. Here's the code -
package readingandwritingfiles;
import java.io.*;
public class ShowFile {
public static void main(String[] args) throws Exception{
int i;
FileInputStream file_IN;
try {
file_IN = new FileInputStream(args[0]);
}
catch(FileNotFoundException e) {
System.out.println("File Not Found!");
return;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
do {
i = file_IN.read();
if(i != -1)
System.out.print((char)i);
} while(i != -1);
file_IN.close();
System.exit(0);
}
}
If you are just putting Test.txt then the program is looking in the root folder of the project. Example:
Project
-src
--package
---class
-bin
-Test.txt
Test.txt needs to be in the same directory as src and bin, not inside of them
If your folder structure is like this (The Text.txt file inside src folder)
+src
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("Text.txt").getFile());
file_IN = new FileInputStream(file);
Or If your folder structure is like this
+src
+somepackage
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("/somepackage/Text.txt").getFile());
file_IN = new FileInputStream(file);
Pass a String (or File) with the relative path to your project folder (if you have your file inside src folder, this should be "src/Test.txt", not "Test.txt").
For read a text file you should use FileReader and BufferedReader, BufferedReader have methods for read completed lines, you can read until you found null.
An example:
String path = "src/Test.txt";
try {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception ex) {
}
Tons of ways to accomplish this! I noticed that you specify args[0], why?
// Java Program to illustrate reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
public static void main(String[] args) throws Exception
{
// pass the path to the file as a parameter
File file =
new File("C:\\Users\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}

BuferredReader problems

I am having trouble reading from a file. Here is my code can anyone show me where I am wrong?
public static Map<Route, List<Service>> read(String fileName)
throws IOException, FormatException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String strLine;
while((strLine = reader.readLine())!= null)
{
/* Own Code */
}
reader.close();
}
I am having a FileNotFound Exception. May this be a the location of my file that is wrong?
You seem to want to use a resource. A resource is not accessed as a file, it is better to use it as a stream.
InputStream resourceStream = MyClass.class.getResourceAsStream(fileName);
BufferedReader myReader = new BufferedReader(new InputStreamReader(resourceStream));
Above code takes the location of your class in account, so you can simply use the fileName as is, without a path, and place the fileName next to your .java file. It will automatically be placed next to the generated .class files and - when packaged - in your .jar file.
Just as owlstead commented keep in appropriate location and try like this
URL url = ClassLoader.getSystemResource(fileName);
br = new BufferedReader(new InputStreamReader(url.openStream()));
i.e keep the file in classes folder or bundle with jar or current working directory etc.

Java Reading textfile in Runnable JAR file ERROR

I have to make a project for school; it's a game. I load the map from a text file. Currently I do it with a scanner, but I can't manage to get it working in a Runnable JAR file without putting the res file next to the JAR file. I want to get the text file inside; it worked with BufferedImages, but the text file doesn't work. I have this code:
public String ReadTextFile(String path) throws IOException {
String HoldsText= null;
FileReader fr = new FileReader(getClass().getResource(path).toString());
BufferedReader br = new BufferedReader(fr);
while((HoldsText = br.readLine())!= null){
System.out.println(HoldsText);
}
return HoldsText;
}
path = "res/Maps/Map2.txt"
error:
java.lang.NullPointerException
at aMAZEing.TextManager.ReadTextFile(TextManager.java:22)
at aMAZEing.Map.openFile(Map.java:89)
at aMAZEing.Map.<init>(Map.java:31)
at aMAZEing.Board.<init>(Board.java:50)
at aMAZEing.Maze.<init>(Maze.java:24)
at aMAZEing.Maze.main(Maze.java:15)
file structure: http://speedcap.net/sharing/screen.php?id=files/a9/77/a977e8b487f21e67db941a96087561cd.png
This doesn't seem to work though. I've researched a lot but could not find anything that worked for me. I just need the whole text file in a string, the rest is easy with substring and so on.
EDIT!:
The resolution to this was that my path had res in it, and it didn't work because of that. I deleted the res and got "/Maps/Map2.txt" as path, now the file loads and my map is displayed again.
public static String ReadTextFile(String path) throws IOException{
String HoldsText= null;
InputStream is = getClass().getResourceAsStream(path);
InputStreamReader fr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
while((HoldsText = br.readLine())!= null){
sb.append(HoldsText)
.append("\n");
}
return sb.toString();
}
You need to append the lines and use InputStreamReader instead of FileReader

Categories

Resources