How to accept command line arguments for files - java

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);

Related

Same File giving different output on intellij and cmd

A friend of mine was having some issues with her project,she sent the files for me to debug. I am not sure but from the looks of it she doesn't use any ide, so when I got the files I made an Intellij project and copy pasted the files there.
When I ran the files on intellij it gave me a filenotfound exception, that was not been given in cmd.So I added the correct file path.
the file involves multithreading.
After that, I ran the file on intellij and it gave the desired output.
However, the file is giving a completely different output if I run it from cmd.
//This is the part from main where a thread is being made
Event e = new Restart(gc, 0, filename);
gc.addEvent(e);
new Thread(e).start();
In the restart class there is where the issue was:
public void getEvents(String filename) {
// open the file and read it using Scanner
try {
/** The file containing event details */
File myFile = new File(filename);
/** The Scanner object to read file */
Scanner myReader = new Scanner(myFile);
/** Current event being analyzed by Scanner */
String myEvent;
/** The delay with which the event will occur in ms */
long delayTime;
while ((myReader.hasNextLine())
&& ((myEvent = myReader.nextLine()) != null)) {
int equal = myEvent.indexOf('=');
int comma = myEvent.indexOf(',');
String className = myEvent.substring(equal+1, comma);
myEvent = myEvent.substring(comma+1);
Event e;
if (myEvent.contains("rings")) {
equal = myEvent.indexOf("=");
comma = myEvent.indexOf(",");
delayTime = Long.parseLong(myEvent.substring(equal+1, comma));
myEvent = myEvent.substring(comma+1);
equal = myEvent.indexOf("=");
int rings = Integer.parseInt(myEvent.substring(equal+1));
e = new Bell(delayTime);
gc.addEvent(e);
new Thread(e).start();
while(rings-- > 1) {
e = new Bell(delayTime += 2000);
gc.addEvent(e);
new Thread(e).start();
}
}
else {
equal = myEvent.indexOf("=");
delayTime = Long.parseLong(myEvent.substring(equal+1));
Class<Event> myClass = (Class<Event>)Class.forName("tme4." + className);
Constructor<Event> ctor = myClass.getConstructor(long.class);
e = ctor.newInstance(delayTime);
gc.addEvent(e);
new Thread(e).start();
}
}
myReader.close();
} catch (Exception e) {
e.printStackTrace();;
}
}
I only changed the first few lines:
From This:
File myFile = new File(filename);
/** The Scanner object to read file */
Scanner myReader = new Scanner(myFile);
Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(),filename);
To This:
filePath=Paths.get("C:\\Users\\Admin\\IdeaProjects\\summayah\\src\\examples1.txt");
System.out.println(filePath);
File myFile = new File(filename);
/** The Scanner object to read file */
Scanner myReader = new Scanner(myFile);
Can someone kindly help me? Thanks in advance

createNewFile() Throws FileNotFoundException When Given the Correct FilePath

Here is my code below:
public void playerNaming() throws IOException {
Scanner pickName = new Scanner(System.in);
System.out.println("What do you want your username to be?");
String playerName = pickName.nextLine();
userName = playerName;
File file1 = new File("PlayerFiles\\" + playerName + ".txt");
File file2 = new File(file1.getAbsolutePath());
System.out.println(file2);
file2.createNewFile();
BufferedWriter file3 = new BufferedWriter(new FileWriter(file2));
}
On line file2.createNewFile(); It throws
java.io.FileNotFoundException: (Insert correct FilePath here) The system cannot find the path specified
What is wrong? According to all the articles and other stackoverflow questions I have read, this should work.
Check your file path :
public static void main(String args[])
{
try {
// Get the file
File f = new File("F:\\program1.txt");
// Create new file
// if it does not exist
if (f.createNewFile())
System.out.println("File created");
else
System.out.println("File already exists");
}
catch (Exception e) {
System.err.println(e);
}
Note : The file “F:\program.txt” is a existing file in F: Directory.

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

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.

Get the path when run from terminal or command line

I am trying to make a program that will be run from terminal or command line. You will have to supply a file name in the arguments. I want it to be able to get the path in which the program was run and then append the file name to it. It would be something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (args.length > 0) {
if (args[0] instanceof String && !args[0].equals(null)) {
if (args[0].equals("compile")) {
System.out.println("File to compile:");
String fileName = scanner.next();
String path = /*get the path here*/ + fileName;
File textfile = new File(path);
if (textfile.exists()) {
Compiler compiler = new Compiler(textfile);
compiler.compile();
} else {
System.out.println("File doesn't exist");
}
}
}
}
}
This should work for you:
Paths.get("").toAbsolutePath().toString()
You can test by:
System.out.println("" + Paths.get("").toAbsolutePath().toString());
Try this:
String path = System.getProperty("user.dir") + "/" + fileName;
If i understand you correctly you are trying to get the path where the program is located.
if so you can try the following:
URI path = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath().toURI());
Replacing /*get the path here*/ with Paths.get(".") should get you what you want. If your argument is a filename in the same directory you don't have to provide a path to it to create the File object.
So in your case,
File textfile = new File(fileName);
should work as well.

Reading filepath from properties file

I'm trying to read a file from a filepath read from properties, but I keep getting FileNotFoundException (the file exists).
test.properties:
test.value = "src/main/resources/File.csv"
LoadProperties.java:
public class LoadProperties {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties aProp = new Properties();
aProp.load(new FileInputStream("src/main/resources/test.properties")); // works
String filepath = aProp.getProperty("test.value");
System.out.println(filepath); // outputs: "src/main/resources/File.csv"
FileReader aReader = new FileReader("src/main/resources/File.csv"); // works
FileReader aReader2 = new FileReader(filepath); // java.io.FileNotFoundException
}
}
Why is this exception being thrown while the line above it works just fine?
How should I read a file from a path provided with properties?
You are not supposed to put " in your property file. Here Java sees it as :
String file = "\"src/main/resources/File.csv\"";
test.value =src/main/resources/File.csv
You don't need double quotes in properties file to represent a continuous string.
you can write own logic to read properties file, it does not matter whether single quotes or double quotes are there in the file path
String propertyFileLocation = "C:\a\b\c\abc.properties";
try
{
fileInputStream = new FileInputStream(propertyFileLocation);
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
properties = new Properties();
String currentLine = null;
String[] keyValueArray = null;
while ((currentLine = bufferedReader.readLine()) != null) {
if (!currentLine.trim().startsWith("#")) {
keyValueArray = currentLine.split("=");
if (keyValueArray.length > 1) {
properties.put(keyValueArray[0].trim(), keyValueArray[1].trim().replace("\\\\","\\"));
}
}
}
}
catch (Exception e)
{
return null;
}

Categories

Resources