create .jar that reads multiple files given by user - java

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

Related

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

User enters what the file name is they want to read in?

For the purpose of this class task, we have been asked to make a program that uses the File Class(I know input stream is much better) but yeah, we have to ask the user to input the name of the .txt file.
public class input {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
String name;
int lineCount = 0;
int wordCount = 0;
System.out.println("Please type the file you want to read in: ");
name = s.next();
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
How would I get
File input = new File(...);
to search for the file as just typing 'lab1task3' doesn't work.
edit: error -
Exception in thread "main" java.io.FileNotFoundException: \lab1task3.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at inputoutput.input.main(input.java:19)
Scanner can't read in files that way, you need to store it as a file first!
If you put this inside of a try-catch block, you can ensure that the program won't break if a file isn't found. I would suggest wrapping it in a do-while/while loop (depending on structure), with the end condition being that the file is found.
I changed your main method to this and it compiles correctly:
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner (System.in);
System.out.println("Please type the file you want to read in: ");
String fname = sc.nextLine();
File file = new File (fname);
sc.close();
}
To search for a file inside a specific folder, you could just iterate over the files inside the given folder via:
File givenFolder = new File(...);
String fileName = (...);
File toSearch = findFile(givenFolder, fileName);
Where the function findFile(File folder, String fileName) would iterate over the files in the givenFolder and try to find the file. It could look like this:
public File findFile(File givenFolder, String fileName)
{
List<File> files = getFiles();
for(File f : files)
{
if(f.getName().equals(fileName))
{
return f;
}
}
return null;
}
The function getFiles is just iterating over all files in the given folder and calls it self when finding a folder:
public List<File> getFiles(File givenFolder)
{
List<File> files = new ArrayList<File>();
for(File f : givenFolder.listFiles())
{
if(f.isDirectory())
{
files.addAll(getFiles(f));
}
else
{
files.add(f);
}
}
}
I hope this helps you :) If you want to know more about what happens here exactly feel free to ask :)

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.

File that exists is not being found in Java

I have a Java program that searches through your cookies files and then saves each file into an array. I then try to search through each of those files for a certain string, however when I try to search the files I KNOW exist, java tells me that they don't. Any ideas?
Here is my code so far:
import java.io.*;
import java.util.*;
public class CheckCookie
{
static String[] textFiles = new String[100];
static String userName = "";
public static void findCookies()
{
String path = "pathtocookies";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
textFiles[i] = files;
}
}
}
}
public static boolean searchCookies()
{
for(int j = 0; j < textFiles.length; j++) {
String path2 = "pathtocookies"+textFiles[j];
File file = new File(path2);
try {
Scanner scan = new Scanner(file);
while (scan.hasNext()) {
String line = scan.nextLine();
if(line.contains("ineligible_age")) {
System.out.println("A cookie for ineligible age was set.");
return true;
}
}
}
catch(FileNotFoundException e) {
System.out.println("File was not found.");
return false;
}
}
System.out.println("A cookie for ineligible age was not set.");
return false;
}
public static void main(String[] args)
{
findCookies();
searchCookies();
System.out.println();
System.out.println("Finished searching for cookies. Yum.");
}
}
Actual path:
C:/Users/lucas.brandt/AppData/Roaming/Microsoft/Windows/Cookies
Use a List, instead of an array to store the textFiles.
Imagine a directory with 2 files. The first is "abc.doc", the second "itsme.txt"
Your textFiles array will look like this:
textFiles[0]: null
textFiles[1]: "itsme.txt"
So you try to access "pathtocookies" + "null" which will fail, you go to the catch and return out of the function.
Further hints:
Return the list from the first function, use it as an argument for the second function
Use a debugger or "debug" print statements to debug your code to see whats happening
More hints depends on the actual use case.
--tb
In this line:
String path2 = "pathtocookies"+textFiles[j];
You are missing the File separator between the directory name and the file name. java.io.File has a constructor that takes the parent path and the file name as separate arguments. You can use that or insert File.separator:
String path2 = "pathtocookies" + File.separator + textFiles[j];
You are also picking up directories in your array. Check that it is a file before you try to scan it.
Also, consider the other answer where the files are saved in a List, eliminating the directories.
files = listOfFiles[i].getName();
Try to change to
files = listOfFiles[i].getAbsolutePath();
EDIT
You can also initiate directectly an array of File (instead of String),
and you have to use .canRead() method to verify File access.
Why don't you just store the File instances in a File[] or List<File>?
I think you would also benefot from using a StringBuilder, when doing a lot of string concatenstions...

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