So I have a file with a list of users in the format like this:
michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash
abigail:&i4KZ5wmac566:501:501:Abigail Smith:/home/abigail:/bin/tcsh
What I need to do is just extract the passwords from the file which in this case are:
"atbWfKL4etk4U" and "&i4KZ5wmac566" and to store them into an array.
This is what I have so far:
public static void main(String[] args) throws IOException{
// Create a scanner for keyboard input
Scanner scan = new Scanner(System.in);
// Prompt user to select a file to open
System.out.print("Enter the path of the file: ");
String filename = scan.nextLine();
// Open the file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Create Array to store each user password in
String[] passwords = {};
// Close the file
scan.close();
inputFile.close();
}
public static void main(String[] args) throws IOException{
// Create a scanner for keyboard input
Scanner scan = new Scanner(System.in);
// Prompt user to select a file to open
System.out.print("Enter the path of the file: ");
String filename = scan.nextLine();
// Open the file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
List<String> passwords = new ArrayList<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String password = line.split(":")[1];
passwords.add(password);
}
// Close the file
scan.close();
inputFile.close();
}
If instead you rather store username and password (assuming the first token is the user name), create a Map instead of a List.
Map<String, String> passwordMap = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] tokens = line.split(":");
passwordMap.put(tokens[0], tokens[1]);
}
You could read the file line by line using a Scanner object.
Then, you use another Scanner object to read the password. Here's an example:
String input = "michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash";
Scanner s = new Scanner(input).useDelimiter(":");
s.next(); //skipping username
String password = s.next();
This looks like a typical CSV type file format and because there is an unknown number of Users in the file and the fact that arrays can not dynamically grow it's a good idea to utilize an ArrayList which can grow dynamically and then convert that list to a String array, for example:
The following method assumes there is No Header Line within the data file:
public static String[] getPasswordsFromFile(String filePath) {
List<String> passwordsList = new ArrayList<>();
File file = new File(filePath);
try (Scanner reader = new Scanner(file)) {
String line = "";
while (reader.hasNextLine()) {
line = reader.nextLine().trim();
// Skip blank lines (if any).
if (line.isEmpty()) {
continue;
}
/* Split out the password from the file data line:
The Regular Expression (RegEx) below splits each
encountered file line based on the Colon(:) delimiter
but also handles any possible whitespaces before
or after that delimiter: */
String linePassword = line.split("\\s*\\:\\s*")[1];
// If there is no password there then apply "N/A":
if (linePassword.isEmpty()) {
linePassword = "N/A";
}
// Add the password to the List
passwordsList.add(linePassword);
}
}
catch (FileNotFoundException ex) {
// Handle the exception (if any) the way you like...
System.err.println(ex.getMessage());
}
// Convert the List<String> to String[] Array and return:
return passwordsList.toArray(new String[passwordsList.size()]);
}
How you might use a method like this:
// Create a scanner object for keyboard input
Scanner userInput = new Scanner(System.in);
// Prompt user to select a file to open with validation:
String fileName = "";
// -----------------------------------
while (fileName.isEmpty()) {
System.out.print("Enter the path of the file (c to cancel): --> ");
fileName = userInput.nextLine();
if (fileName.equalsIgnoreCase("c")) {
System.out.println("Process Canceled! Quiting.");
System.exit(0);
}
if (!new File(fileName).exists()) {
System.out.println("Invalid Entry! Try again...\n");
fileName = "";
}
}
// -----------------------------------
/* OR - you could have........
// -----------------------------------
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new File("").getAbsolutePath());
fc.showDialog(new JDialog(), "get Passwords");
if (fc.getSelectedFile() != null) {
fileName = fc.getSelectedFile().getAbsolutePath();
}
else {
System.out.println("Process Canceled! Quiting.");
System.exit(0);
}
// -----------------------------------
*/
// Get the Passwords from file:
String[] passwords = getPasswordsFromFile("UserData.txt");
// Display the Passwords retrieved:
System.out.println();
System.out.println("Passwords from file:");
System.out.println("====================");
for (String str : passwords) {
System.out.println(str);
}
If you were to run this code against a file which contains the data you provided within your post,your console window will diplay:
Enter the path of the file (c to cancel): --> userData.txt
Passwords from file:
====================
atbWfKL4etk4U
&i4KZ5wmac566
Related
so I want to read in a text file with a bunch of inputs containing strings like this:
abc456
mnjk452
aaliee23345
poitt78
I want to put each of these inputs into an array list and pass that arraylist through one of my methods. How would I go about doing so? Currently in my code, I'm trying to see if i can simply print out what's in my arraylist. Here is what i have in my main:
public static void main(String[] args) {
if(args.length < 1) {
System.out.println("Give me a file!");
}
String fname = args[0];
ArrayList<String> coordinates = new ArrayList<String>();
Scanner grid = new Scanner(fname);
while(grid.hasNext()) {
coordinates.add(grid.nextLine());
}
for(String coordinate : coordinates) {
System.out.println(coordinate);
}
}
How about this:
Path path = Paths.get(args[0]);
List<String> coordinates = Files.readAllLines(path);
System.out.print(coordinates); // [abc456, mnjk452, aaliee23345, poitt78]
Same can be accomplished with the Scanner:
Path path = Paths.get(args[0]);
List<String> result = new ArrayList<>();
Scanner sc = new Scanner(path);
while (sc.hasNextLine()) {
String line = sc.nextLine();
result.add(line);
}
System.out.print(result); // [abc456, mnjk452, aaliee23345, poitt78]
Do not forget to pass your arguments when you run your application (either in your IDE or command line)!
When reading from a file you need to create a File object that you give to the Scanner object. Also you should control your while loop based on grid.hasNextLine() since you are grabbing line by line. Lastly when running the program from terminal you should be doing the following
java "name of your class with main" "file name"
Which will pass that file in as a parameter to args[0]
try
{
Scanner grid = new Scanner(new File(fname));
while(grid.hasNextLine())
{
coordinates.add(grid.nextLine());
}
}catch(FileNotFoundException e)
{
System.err.println("File " + fname + " does not exist/could not be found");
e.printStackTrace();
}
I am trying to run this code and I get error as the system cannot find the file specified. My file is in the same directory as the code. I am specifying the full path name also. So what is the problem?
public class StopWordsSol
{
public static void main(String[] arg)
{
Scanner keyboard = new Scanner(System.in);
// ask for the stop words file name and read in stop words
System.out.print("Please type the stop words file name: ");
String[] stopWords = readStopWords(keyboard.next());
// ask for the text file and remove stop words
System.out.print("Please type the text file name: ");
removeStopWords(keyboard.next(), stopWords);
}
// read stop words from the file and return an array of stop words
public static String[] readStopWords(String stopWordsFilename)
{
String[] stopWords = null;
try
{
Scanner stopWordsFile = new Scanner(new File(stopWordsFilename));
int numStopWords = stopWordsFile.nextInt();
stopWords = new String[numStopWords];
for (int i = 0; i < numStopWords; i++)
stopWords[i] = stopWordsFile.next();
stopWordsFile.close();
}
catch (FileNotFoundException e)
{
System.err.println(e.getMessage());
System.exit(-1);
}
return stopWords;
}
}
This is a quite common problem: the base-directory of the program is usually not the same as the directory the source-code is stored in. Try the following lines:
Path cd = Paths.get("");
System.out.println("cd= " + cd.toAbsolutePath());
Which will print the working-directory of your program.
Im trying to write a program that will ask for the name of an input file and an output file. It will open the input file and create the output file. It will then read the input file and make a double-spaced copy of the input in the output file.
public class ProgramTest
public static void main (String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("where to read?");
String in = keyboard.nextLine();
System.out.println("where to write?");
String out = keyboard.nextLine();
Scanner scanner = new Scanner(new File(in));
PrintWriter outputFile = new PrintWriter(out);
}
Thats what I have so far. What I dont know is how to make it do the last part to read the input file and make a double-spaced copy of the input in the output file.
well you can start by reading in the file?
private static void readFile(String inputFile) {
File file = new File(inputFile);
try {
Scanner scan = new Scanner(file);
//for example String s = scan.next(); would store next word
//doulbe d = scan.nextDouble(); would grab next double
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Once you read in the file sore the lines/numbers into variables?? Should not be to hard work with the read file i provided. Also remember what should you read in first ints or strings?
Im trying to read N different CSV files containing stock price data. I want to extract one particular column from each file and showcase those columns in a single CSV file.
The issue is the combined file contains only the written data from the first file I give as input i.e. that data is not being overwritten in the iteration of my loop.
Can someone help? Or suggest a new method?
public static void main(String[] args) throws IOException
{
int filecount=0;
System.out.println("Enter Number of Files");
Scanner stream =new Scanner(new InputStreamReader(System.in));
filecount= Integer.parseInt(stream.next());
File file2 = new File("Combined_Sym.csv");
FileWriter fwriter= new FileWriter("Combined_Sym.csv",true);
PrintWriter outputFile= new PrintWriter(fwriter);
int i;
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
File file = new File(fileName);
Scanner inputStream = new Scanner(file);
Scanner inputStream2= new Scanner(file2);
if(!inputStream2.hasNext()){
outputFile.println(fileName);
}
else
{ String header=inputStream2.next();
System.out.println(header+","+fileName);
outputFile.println(header+","+fileName);
}
while(inputStream.hasNext())
{
String data= inputStream.next();
String[] values = new String[8];
values = data.split(",");
String sym=values[7];
if(!inputStream2.hasNext())
outputFile.println(sym);
else
{
String data2= inputStream2.next();
outputFile.println(data2+","+sym);
System.out.println(data2+","+sym);
}
}
inputStream.close();
inputStream2.close();
outputFile.close();
}
}
}
Can you try changing :
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
File file = new File(fileName);
to
File file;
for(i=0;i<filecount;i++)
{
System.out.println("Enter File name "+i);
String fileName =stream.next();
file = new File(fileName);
a:b:c:d:e
bb:cc:dd:ee:ff
ccc:ddd:eee:fff:ggg
I have a textfile content above. I am trying to compare my user input with the text file. For example
cc:dd
When it is found, I need to retrieve the entire line. How can I retrieve the line which my user input? I have tried using while(scanner.hasNext()) but I could not get my desire outcome.
With standard Java libraries:
File file = new File("file.txt");
String word = "abc";
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch(FileNotFoundException e) {
//handle this
}
//now read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains(word)) {
System.out.println(line);
}
}
scanner.close();