Issue
I am trying to create a service that parse's each line of a CSV file and runs a variety of booleans for the string on each line. Everything is working correctly but the way I have it set up is that the user copies the text in the CSV file and pastes it into the scanner. I want to make it so that the user can add a CSV file while the code is running.
The way I have it set up right now:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner exampleString = new Scanner(System.in);
do {
String checkString = exampleString.nextLine();
boolean testOne = checkString.contains("Text from CSV line");
if(testOne){
String removingExtraCharacters = checkString.replaceAll
(" [^\\d.$]", "");
System.out.println(removingExtraCharacters);
}
}while (exampleString.hasNextLine());
exampleString.close();
}
}
I looked into using the Scanner(File()) method but I could only figure out how to put the file into it before running the code. Is there any way to make it ask the user to add the file to the Scanner after the code is ran?
Solution
What you can do with the Scanner is ask for the destination of the new CSV file, parse that to a string and use the FileReaders to read the contents of the file.
For example:
Scanner scanner = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter .csv filepath");
String filepath = scanner.nextLine();
List<String> contents = Files.readAllLines(Paths.get(filepath));
You however have to change some of this code to make it work. As the Paths.get(filepath)
only looks from the directory where you start the terminal (same folder).
When you run this when a file like text.txt
(or csv for that matter) with ./text.txt
as input it will get all the lines of the file and put it in the list.
Will this work for you?
Answered By - NLxDoDge