Reputation: 597
I'm working on an address book program, and the last thing I'm trying to do is allow the user to specify a file that is full of commands such as: Add 'Name', Delete ' Name, Print, and so on.
All of these methods are implemented into my program already and they work when I type the commands into the console.
I've tried using a for loop that reads the commands from a file input stream, however it only ever processes the first command inside of the csv file. I've even tried adding the commands listed into a String Array first and then reading from the stream array and I get the same result.
Here is what my current code looks like that will process the first command, but nothing else.
private static void fileCommand(String file) throws IOException {
File commandFile = new File(file);
try {
FileInputStream fis = new FileInputStream(commandFile);
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
StringBuilder builder = new StringBuilder();
int ch;
while((ch = fis.read()) != -1){
builder.append((char)ch);
}
ArrayList<String> commands = new ArrayList<String>();
commands.add(builder.toString());
for(int i = 0; i<commands.size();i++){
if (commands.get(i).toUpperCase().startsWith("ADD")|| commands.get(i).toUpperCase().startsWith("DD")){
addBook(commands.get(i));
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
Upvotes: 0
Views: 746
Reputation: 11909
You are adding just one string with all the file's contents into the array. I'm not sure exactly what you csv-file looks like but try this instead:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class SOQuestion {
private static void fileCommand(String file) throws IOException {
Path pathFile = Paths.get(file);
List<String> allLines = Files.readAllLines(pathFile, StandardCharsets.UTF_8);
for (String line : allLines) {
if (line.toUpperCase().startsWith("ADD")) {
addBook(line);
}
}
}
private static void addBook(String line) {
//Do your thing here
System.out.println("command: "+line);
}
public static void main(String[] args) throws IOException {
fileCommand("e:/test.csv"); //just for my testing, change to your stuff
}
}
Assuming your csv-file has one command for each line and the actual command is the first part for each line.
Upvotes: 1