How to store user input from a command line into a txt file in java I am writing
ID: 3765192 • Letter: H
Question
How to store user input from a command line into a txt file in java
I am writing a method/command called "net user" that when the user writes in: "net user john bluutable" to the console the method should store the last two words as a user name and password. "john" being the username and "bluutable" being the password. This command should save the new username and password into a file "myaccount.txt"
I am having trouble figuring out how I would parse the string so that it will only store the third and forth word and then how I would store the contents into a file. Any help is appreciated
Explanation / Answer
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/**
* @author Srinivas Palli
*
*/
public class TextFileOperations {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedWriter bw = null;
try {
File file = new File("myaccount.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the Command:");
String command = scanner.nextLine();
String commandArry[] = command.split(" ");
String content = "";
if (commandArry.length == 4) {
content = commandArry[2] + " " + commandArry[3];
bw.write(content);
} else {
System.out.println("Invalid Command");
}
} catch (FileNotFoundException fie) {
} catch (Exception e) {
} finally {
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
myaccount.txt:
john bluutable
OUTPUT:
Enter the Command:net user john bluutable
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.