问题
public static void main(String[] args) throws IOException{
if (args.length == 1)
{
BufferedReader bf = new BufferedReader (new FileReader("fruit.txt"));
int linecount = 0;
String line;
//run thur the txt file to check if input exist
while (( line = bf.readLine()) != null)
{
linecount++;
int indexfound = line.indexOf(args[0]);
if (indexfound > -1) {
System.out.println("fruit exist on line " + linecount);
System.out.println("add another fruit");
System.exit(0);
} else {
BufferedWriter bw = new BufferedWriter(new FileWriter("fruit.txt", true));
String fruit = "";
fruit = args[0];
bw.write("\r\n" + fruit);
System.out.println(fruit+ "added");
}
}
f.close();
bw.close();
}
I want to have the program to search in a text file fruit.txt check if a fruit already exist in it.
if fruit exist then prompt user to input another 1
else add in to the nextline of the text file
This is what I got so far. but I am not sure why it isnt what I wanted.
in my text file it started with 3 fruit
apple
orange
pear
after i add in berry
apple
orange
pear
berry
berry
after i add in melon
apple
orange
pear
berry
berry
melon
melon
melon
melon
回答1:
You are just checking for the fruit in the first line, and if it is not found, you are continuing to add it.
You need to read your file completely first, one for checking each line, that it contains your fruit or not, and then if it does not contain, just dump that fruit in it. And if it contains, reject it.
So, in your while, you need to move that else part outside. And rather than doing System.exit() when fruit is found, you can set a boolean variable to true, and then later on, based on the value of boolean variable, you can decide whether to add the fruit or not.
boolean found = false;
while (( line = bf.readLine()) != null) {
linecount++;
int indexfound = line.indexOf(args[0]);
if (indexfound > -1) {
System.out.println("fruit exist on line " + linecount);
System.out.println("add another fruit");
found = true;
break;
}
}
if (!found) {
BufferedWriter bw = new BufferedWriter(new FileWriter("fruit.txt", true));
String fruit = "";
fruit = args[0];
bw.write("\r\n" + fruit);
System.out.println(fruit+ "added");
bw.close(); // You need to close it here only.
}
bf.close();
来源:https://stackoverflow.com/questions/13044259/method-to-find-string-in-text-file-then-add-in-string-to-text-file-if-string-is