Get the path when run from terminal or command line - java

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.

Related

How to rename instances of filepath scattered throughout program based on user input?

I'm pretty new to Java, so apologies if this question seems dumb, I've tried google but there's not really anything on there that matches what I'm looking for.
I am trying to get my program to take in user input and rename .txt files linked to the program with their input. My only issue is, I don't know how I would then take that input and update all the named instances of the filepath across the program. For the most part, I am passing the filepath into methods for usage, but the initial variable of filepath I have declared as a String.
Any advice on the most efficient way to update all instances of this variable at once with the new file name?
String filepath = "src/file.txt";
Here is the code I currently have for editing the file name:
public static void fileRename(){
String oldFileName = "";
String newFileName = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter old File name: ");
System.out.println("Formatted as: src/oldFileName.csv");
oldFileName = in.next();
System.out.println("Please enter new File name: ");
System.out.println("Formatted as: src/newFileName.csv");
newFileName = in.next();
File oldFile = new File(oldFileName);
File newFile = new File(newFileName);
oldFile.renameTo(newFile);
// sets filepath variable across program equal to newFileName
}
Once the user has renamed the file, I am struggling with then updating the filepath variable across the program, as it occurs multiple times within the program.
String targetExtension = ".txt";
if (args.length >= 1 ) {
int extIndex = args[0].lastIndexOf(".");
if (extIndex != -1) {
String ext = args[0].substring(extIndex);
System.out.println(ext);
if (ext.equalsIgnoreCase(".xml")){
try
{
File f = new File(args[0]);
if (!f.exists())
{
f.createNewFile();
}
args[0] = args[0].substring(0, extIndex) + targetExtension;
System.out.println(" " + args[0]);
File change = new File(args[0]);
f.renameTo(change);
}catch (IOException e)
{
e.printStackTrace();
}
}
}
you can use elseif for all the extension.

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

create .jar that reads multiple files given by user

I am trying to make a single .jar executable file that reads .txt file and print some value.
my issue is that I don't want to specify the .txt file name before making the .jar, I want to pass the .jar to the user and each time before he run the .jar he will specify the desired .txt file to be read.
is there any way to do that?
You can get the command line argument from the String array passed to your Main method.
public static void main(String[] args) {
if (args.length <= 0) {
System.out.println("No arguments specified");
return;
}
String filename = args[0];
if (filename.trim().length() <= 0) {
System.out.println("Filename is empty");
return;
}
File file = new File(filename);
if (!file.exists()) {
System.out.println("File doesn't exist");
return
}
// Do what you want with the file here
}
If you want multiple files, you can do this by breaking each commandline argument into another file
public static void main(String[] args) {
if (args.length <= 0) {
System.out.println("No arguments specified");
return;
}
List<File> files = new ArrayList<>();
for (String filename : args) {
File file = new File(filename);
if (!file.exists()) {
System.out.println("File doesn't exist");
continue;
}
files.add(file);
}
// Do what you want with your list of files here
}
You can make the user to insert the file name and the program adds it to the searching route ex: "C:\"+textname

How to get file extension?

Here is my code that I have developed but I got stuck on one thing. I want to make my program recognize what file extension is the file within my directory.
import java.io.File;
public class SystemCommands{
public static void main (String args[]){
String dir_name = "C:\\Program Files\\WinRAR";
File dir = new File(dir_name);
File[] dir_list = dir.listFiles();
for(int i=0;i<dir_list.length;++i)
{
System.out.println(dir_list[i].getName());
System.out.println("Is it a directory = " + dir_list[i].isDirectory());
System.out.println("Is it a file = " + dir_list[i].isFile());
}
}
}
You can use String#lastIndexOf and simply do:
String file = dir_list[i].toString();
System.out.println(file.substring(0, file.lastIndexOf('.')));
Or, preferable, you can use FilenameUtils#getExtension:
System.out.println(FilenameUtils.getExtension(yourString));
String filename=null;
for(int i=0;i<dir_list.length;++i)
{
filename=dir_list[i].getName();
if(dir_list[i].isFile())
{
System.out.println(filename.split(\\.)[(filename.split(\\.)).length-1]);
}
}
Use FilenameUtils.getExtension from Apache Commons IO
Here is an example of use:
String ext = FilenameUtils.getExtension("/path/file/file.txt");
Try this one...
File fileName= new File("Animation.xml");
String str= fileName.getName();
System.out.println(fileName.getName());
System.out.println(str.substring(str.lastIndexOf(".")));
File f = new File("test.txt");
String [] str = f.getName().split("\\.");
if(str.length>1) {
System.out.println(str[1]);
}else {
System.out.println("No extension. File name is :" + str[0]);
}

how to know invalid path to save the file in java

In Java I want to create a file from and save the data on it. The File name with path is taken from user. Now if user give invalid path like C:\temp\./user\fir/st.csv which is an invalid path because "." and / are in the path and on windows operating system "\" is used as path separator.
Before executing the program(a command line tool), there was no temp folder in C:\ directory, but when I run the program it creates temp folder then in temp it creates user then in user it create fir folder and finally st.csv in it. While I want that if such type of invalid path or file name is given by the user user should be noticed by message "Invalid path or file name".
What should I do? Program code is like below:
public class FileTest {
public static void main(String args[]) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter path:");
String path = br.readLine();
File file = new File(path);
String path1 = file.getParent();
File file2 = new File(path1);
if (!file2.exists()) {
System.out.println("Directory does not exist , So creating directory");
file2.mkdirs();
}
if (!file2.exists()) {
System.out.println("Directory can not be created");
} else {
FileWriter writer = new FileWriter(file);
PrintWriter out = new PrintWriter(writer);
System.out.println("Please enter text to write on the file, print exit at new line to if finished");
String line = "";
while ((line = br.readLine()) != null) {
if (line.equalsIgnoreCase("exit")) {
System.out.println("Thanks for using our system");
System.exit(0);
} else {
out.println(line);
out.flush();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Now if I give the path as C:\tump\./user\fir/st.csv then it create tump folder in C drive , then user in tump, then fir in user folder then st.csv file in it.
boolean exists = (new File("filename")).exists();
if (exists) {
// File or directory exists
} else {
// File or directory does not exist
}
PLUS: You must never use hard-coded path separators. You're having problems by that, use instead the static attributes
File.separator - string with file separator
File.separatorChar - char with file separator
File.pathSeparator - string with path separator
File.pathSeparatorChar - char with path separator
Looks very similar to this:
Is there a way in Java to determine if a path is valid without attempting to create a file?
There's a link in one of the answers to here:
http://www.thekua.com/atwork/2008/09/javaiofile-setreadonly-and-canwrite-broken-on-windows/
Which details what could possibly work for you:
By Peter Tsenga
public static boolean canWrite(String path) {
File file = new File(path);
if (!file.canWrite()) {
return false;
}
/* Java lies on Windows */
try {
new FileOutputStream(file, true).close();
} catch (IOException e) {
LOGGER.info(path + ” is not writable: ” + e.getLocalizedMessage());
return false;
}
return true;
}
You mention this is a command line tool. Does that mean it will be always run from the command line, or could it be called from an environment that presumes no further user interaction (like batch file or by Ant)?
From a command line, it is possible to pop a JFileChooser. This is a much better way to accept a file name from the user. It is easier for the user, and more reliable for the program.
Here is an example based on your code:
import java.io.*;
import javax.swing.*;
public class FileTest {
public static void main(String args[]) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal==JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
if (!file.getParentFile().exists()) {
System.out.println("Directory does not exist, creating..");
file.getParentFile().mkdirs();
}
if (!file.getParentFile().exists()) {
System.out.println("Directory can not be created");
} else {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
FileWriter writer = new FileWriter(file);
PrintWriter out = new PrintWriter(writer);
System.out.println("Please enter text to write on the file," +
" print exit at new line to if finished");
String line = "";
while ((line = br.readLine()) != null) {
if (line.equalsIgnoreCase("exit")) {
System.out.println("Thanks for using our system");
System.exit(0);
} else {
out.println(line);
out.flush();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Maybe next time..");
}
}
});
}
}
Note that if I were coding this, I'd then go on to get rid of the InputStreamReader and instead show the text in a JTextArea inside a JFrame, JDialog or (easiest) JOptionPane, with a JButton to invoke saving the edited text. I mean, a command line based file editor? This is the 3rd millennium (damn it!).
In my case which I required this works
if(!path.equals(file.getCanonicalPath())){
System.out.println("FAILED:Either invalid filename, directory or volume label , syntax error");
System.exit(0);
}
By adding this code just after File file=new File(path); it will work fine and will notice the user if given path is incorrect
As there is only two options either java will create the file on some path which will be canonical path or if not able to create the file it will give exception. So if there is any mismatch in the path given by the user and canonical path then it means user type wrong path which java can not create on the file system, so we will notice the user, or if java give exception then we can catch it and will notice the user for incorrect path

Categories

Resources