Enter command with each line from a file - java

I am trying to write a plugin that reads a file line by line and then enters a command in the console with each name as separate commands. This does contain code which relies on the Bukkit API, but it should be simple enough to figure out.
I am currently using a Scanner, but is a BufferedReader would be better, let me know. Currently, the scanner prints fine without the extra Bukkit code.
Current code:
public class FixWhitelist extends JavaPlugin {
public static void main(String[] args) {
FixWhitelist scanner = new FixWhitelist();
scanner.readFile("white-list.txt");
}
public void readFile(String path) {
try {
Scanner sc = new Scanner(new File(path));
while(sc.hasNextLine()) {
String next = sc.nextLine();
//System.out.println(next);
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "whitelist add" + next);
Bukkit.getServer().getConsoleSender().sendMessage(next + "added to the whitelist.");
}
sc.close();
}
catch (FileNotFoundException ex) {
Logger.getLogger(FixWhitelist.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
So, the question is, how can I have a command entered for each line of code in a file?

Should the following line have a space after the "add":
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "whitelist add " + next);

Related

JAVA - Parsing CSV File - Change delimiter

I have a problem and wanted to ask if someone can help me. I have a Java application that processes CSV files. The files have a semi-colon as a "delimiter". Now instead of semicolons I would like to use pipe "|" as the "delimiter". What is the best way to do this?
I have already informed myself in the library or class "org.apache.commons.csv.CSVRecord". Unfortunately couldn't find anything here.
I used for parsing Spring Batch with the class FlatItemReaderBuilder.
You can also use Spring Batch classes in non Spring application.
Here you can find an example:
https://www.petrikainulainen.net/programming/spring-framework/spring-batch-tutorial-reading-information-from-a-file/
you could use Scanner or FileInputStream
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ReadDelimited {
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(new File("D:\\acct.csv"));
// Check if there is another line of input
while(sc.hasNextLine()){
String str = sc.nextLine();
// parse each line using delimiter
parseData(str);
}
} catch (IOException exp) {
// TODO Auto-generated catch block
exp.printStackTrace();
}finally{
if(sc != null)
sc.close();
}
}
private static void parseData(String str){
String acctFrom, acctTo, amount;
Scanner lineScanner = new Scanner(str);
lineScanner.useDelimiter("|");
while(lineScanner.hasNext()){
acctFrom = lineScanner.next();
acctTo = lineScanner.next();
amount = lineScanner.next();
System.out.println("Account From- " + acctFrom + " Account To- " + acctTo +
" Amount- " + amount);
}
lineScanner.close();
}
}
reference Code original link
or if File is not too large get the read the File in a string Divide it into a String array by splitting by line break and then future splitting using the delimiter of choice something like the code below.
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream=new FileInputStream("j:\\test.csv");
String s1=new String(fileInputStream.readAllBytes());
String[] lineArray=s1.split("\n");
List<String[]> separatedValues=new ArrayList<>();
for (String line: lineArray) {
separatedValues.add(line.split("\\|"));
}
for (String[] s: separatedValues) {
for (String s2:s ) {
System.out.print(s2+" ");
}
System.out.println("");
}
fileInputStream.close();
}
Code Output Link
Original CSV

Read and Write to a file

I am having to make a gui project for my CSIS class and I am having trouble with the read and Write I am using. I am making a game where you battle stuff and after you beat five of them it shows a message saying "YOU WIN". Every time you win a battle, I have it write the number of wins to a file so if you were to close the game you can continue when it is opened again. Here is the code that i have Written - this is my read method.
private static int read()
{
int returnValue = 0;
try(Scanner reader = new Scanner("wins.txt"))
{
while(reader.hasNextLine())
{
String read = reader.nextLine();
returnValue = Integer.parseInt(read);
}
}
catch(NullPointerException e)
{
System.out.println("No such File! Please Try Again! " + e.getMessage());
}
return returnValue;
and this is my Write method.
private static void write(int wins)
{
try(Formatter writer = new Formatter("wins.txt");)
{
writer.format("%d", wins);
}
catch (FileNotFoundException e)
{
System.out.println("File not Found!!");
}
}
the only thing that is in the wins.txt file is the number that the Write method writes into it. so i win once then the file will have "1" and if i win twice then it will have "2"
Whenever I run the program, it throws a NumberFormatException. I am not sure why it is doing this because I am parseing the String that that reader reads into an int.
The problem is that this code...
Scanner reader = new Scanner("wins.txt")
... constructs a Scanner with the literal text "wins.txt", not the contents of the file "wins.txt".
To read a file with a Scanner, the easiest way for you is probably to construct it using a File object...
Scanner reader = new Scanner(new File("wins.txt"))
There are some other changes you will need to make to your code to get it to work from this point, but this should cover the major issue.

having issues with Java reading input files using netbeans

Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.

Input a text file through command line in java

I am trying to write a program that inputs a text file through the command line and then prints out the number of words in the text file. I've spent around 5 hours on this already. I'm taking an intro class using java.
Here is my code:
import java.util.*;
import java.io.*;
import java.nio.*;
public class WordCounter
{
private static Scanner input;
public static void main(String[] args)
{
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
openFile();
readRecords();
closeFile();
}
public static void openFile()
{
try
{
input = new Scanner(new File(file));
}
catch (IOException ioException)
{
System.err.println("Cannot open file.");
System.exit(1);
}
}
public static void readRecords()
{
int total = 0;
while (input.hasNext()) // while there is more to read
{
total += 1;
}
System.out.printf("The total number of word without duplication is: %d", total);
}
public static void closeFile()
{
if (input != null)
input.close();
}
}
Each way I've tried I get a different error and the most consistent one is "cannot find symbol" for the file argument in
input = new Scanner(new File(file));
I'm also still not entirely sure what the difference between java.io and java.nio is so I have tried using objects from both. I'm sure this is an obvious problem I just can't see it. I've read a lot of similar posts on here and that is where some of my code is from.
I've gotten the program to compile before but then it freezes in command prompt.
java.nio is the New and improved version of java.io. You can use either for this task. I tested the following code in the command line and it seems to work fine. The "cannot find symbol" error message is resolved in the try block. I think you were confusing the compiler by instantiating a File object named file twice. As #dammina answered, you do need to add the input.next(); to the while loop for the Scanner to proceed to the next word.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class WordCounter {
private static Scanner input;
public static void main(String[] args) {
if(args.length == 0) {
System.out.println("File name not specified.");
System.exit(1);
}
try {
File file = new File(args[0]);
input = new Scanner(file);
} catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
int total = 0;
while (input.hasNext()) {
total += 1;
input.next();
}
System.out.printf("The total number of words without duplication is: %d", total);
input.close();
}
}
Your code is almost correct. Thing is in the while loop you have specified the terminating condition as follows,
while (input.hasNext()) // while there is more to read
However as you are just increment the count without moving to the next word the count just increases by always counting the first word. To make it work just add input.next() into the loop to move to next word in each iteration.
while (input.hasNext()) // while there is more to read
{
total += 1;
input.next();
}

Filewriter and spaces?

I was asked to write an assignment wherein the user would be prompted to input a key and/or a value.
So far, here is my code:
import java.util.Scanner;
import java.io.*;
class bTree
{
//Fields
static Scanner input = new Scanner(System.in);
static boolean done = false;
public static void main(String args[])throws Exception
{
FileWriter fWriter = new FileWriter("data.txt");
do
{
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
if(enter[0].toLowerCase().equals("insert"))
{
fWriter.write(enter[1] + "\n" + enter[2] + "\n");
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("select"))
{
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while(fileInput.hasNext() && done == false)
{
if(fileInput.nextLine().equals(enter[1]))
{
System.out.println(fileInput.nextLine());
done = true;
}
else
{
fileInput.nextLine();
}
}
done = false;
}
else if(enter[0].toLowerCase().equals("update"))
{
fWriter.write(enter[2]);
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("exit"))
{
System.exit(0);
}
}
while(true);
}
}
Problem: When i open the data.txt, there are no spaces. So if i enter "insert 1001 gen" and "10001 genny", in notepad, it would come out as "1001gen10001genny". Any suggestions?
The problem is that notepad.exe is picky about line endings, and there are many possibilities. When you write "\n" to a FileWriter, it writes a single character, namely '\n'. But notepad expects the sequence "\r\n" instead. It shows a single "\n" as nothing.
Here is your code, slightly modified to work around some pitfalls.
package so7696816;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
public class Excercise {
public static void main(String args[]) throws Exception {
final Scanner input = new Scanner(System.in);
PrintWriter fWriter = new PrintWriter("data.txt");
while (true) {
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
final String command = enter[0].toLowerCase(Locale.ROOT);
if (command.equals("insert")) {
fWriter.println(enter[1]);
fWriter.println(enter[2]);
fWriter.flush();
} else if (command.equals("select")) {
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while (fileInput.hasNextLine()) {
String key = fileInput.nextLine();
String value = fileInput.nextLine();
if (key.equals(enter[1])) {
System.out.println(value);
break;
}
}
fReader.close(); // don't leave files open
} else if (command.equals("update")) {
fWriter.write(enter[2]);
fWriter.flush();
} else if (command.equals("exit")) {
return;
} else {
System.err.println("Unknown command: " + command);
}
}
}
}
Remarks:
I used a PrintWriter instead of a FileWriter to get the line endings correct.
For the select command I closed the fReader after using it.
I avoided to type enter[0].toLowerCase() multiple times.
I used the proper variant of toLowerCase.
I added error handling for unknown commands.
I rewrote the select command to be a little more concise.
The problem is String enter[] = input.nextLine().split(" ", 3);, it kills the Spaces. So append a space after each array entry or write an additional " " everytime you use fWriter.write.
look here
As already stated the line feed character is incorrect for notepad. Alternatively you could wrap that FileWriter in a BufferedWriter and use the newLine method to always insert the correct line feed.
I think you are running your program in UNIX. In unix system "\r\n" is the line feed.
If you are running your program in Windows, I think the file should contain something like this.
1001
gen
10001
genny

Categories