Я делаю программу, где просматриваю текстовый файл из 11 имен, проверяю, есть ли в нем определенное имя, добавьте новые имена, удалите имена и закройте файл, чтобы обновить его.
Это данные в каталоге.txt: (каждое имя находится в новой строке)
Майк
Джим
Барри
Cristian
Винсент
Chengjun
Сьюзен
нг
серена
Это каталог моего вспомогательного класса со всеми возможными вещами, которые мы можем сделать с именами.
import java.util.*;
import java.io.*;
public class Directory {
//public static void main(String[] args) {
final int maxDirectorySize = 1024;
String directory[] = new String[maxDirectorySize];
int directorySize = 0;
File directoryFile = null;
Scanner directoryDataIn = null;
public Directory(String directoryFileName) {
directoryFile = new File(directoryFileName);
try {
directoryDataIn = new Scanner(directoryFile);
}
catch (FileNotFoundException e) {
System.out.println("File is not found, exiting!" + directoryFileName);
System.exit(0);
}
while (directoryDataIn.hasNext()) {
directory[directorySize++] = directoryDataIn.nextLine();
}
}
public boolean inDirectory(String name) {
boolean inDir = true;
for (int i = 0; i < directory.length; i++) {
if (name.equalsIgnoreCase(directory[i])) {
inDir = true;
break;
}
else {
inDir = false;
break;
}
}
return inDir;
}
public boolean add(String name) {
if (directory.length == 1024)
return false;
boolean added = true;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
added = false;
break;
}
else {
directory[directorySize++] = name;
added = true;
break;
}
}
return added;
}
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
return false;
}
public void closeDirectory() {
directoryDataIn.close();
PrintStream directoryDataOut = null;
try {
directoryDataOut = new PrintStream(directoryFile);
}
catch (FileNotFoundException e) {
System.out.printf("File %s not found, exiting!", directoryFile);
System.exit(0);
}
String originalDirectory[] = {"Mike","Jim","Barry","Cristian","Vincent","Chengjun","susan","ng","serena"};
if (originalDirectory == directory)
System.exit(0);
else
for (int i = 0; i < directorySize; i++)
directoryDataOut.println(directory[i]);
directoryDataOut.close();
}
}
Это мой класс пользовательского интерфейса, который я запускаю. Класс DirectoryWithObjectDesign
import java.io.*;
import java.util.*;
public class DirectoryWithObjectDesign {
public static void main(String[] args) { //throws IOException
String directoryDataFile = "Directory.txt";
Directory d = new Directory(directoryDataFile);
Scanner stdin = new Scanner(System.in);
System.out.println("Directory Server is Ready!");
System.out.println("Format: command name");
System.out.println("Enter ^Z to end");
while (stdin.hasNext()) {
String command = stdin.next();
String name = stdin.next();
if (command.equalsIgnoreCase("find")) {
if (d.inDirectory(name))
System.out.println(name + " is in the directory");
else
System.out.println(name + " is NOT in the directory");
}
else if (command.equalsIgnoreCase("add")) {
if (d.add(name))
System.out.println(name + " added");
else
System.out.println(name + " cannot add! " + "no more space or already in directory");
}
else if (command.equalsIgnoreCase("delete")) {
if (d.delete(name))
System.out.println(name + " deleted");
else
System.out.println(name + " NOT in directory");
}
else {
System.out.println("bad command, try again");
}
}
}
}
И наконец, вот неисправный вывод, который я получаю:
----jGRASP exec: java DirectoryWithObjectDesign
Directory Server is Ready!
Format: command name
Enter ^Z to end
find mike
mike is in the directory
find serena
serena is NOT in the directory
find susan
susan is NOT in the directory
find barry
barry is NOT in the directory
add melissa
melissa added
add joey
joey added
delete joey
joey NOT in directory
delete ng
ng NOT in directory
delete serena
serena NOT in directory
<eof>
----jGRASP: operation complete.
Я пытался выяснить, как я могу это исправить и попробовать по-разному, но я все равно получаю неправильный результат. Я не вижу, где проблема или как ее исправить... помочь кому-нибудь?
Эта логика неисправна:
public boolean inDirectory(String name) {
boolean inDir = true;
for (int i = 0; i < directory.length; i++) {
if (name.equalsIgnoreCase(directory[i])) {
inDir = true;
break;
}
else {
inDir = false;
break;
}
}
return inDir;
}
Вы найдете только имя, если это имя в каталоге.
Вы должны только выйти из цикла после поиска соответствия или после проверки всех имен в каталоге:
public boolean inDirectory(String name) {
boolean inDir = false;
for (int i = 0; i < directory.length; i++) {
if (name.equalsIgnoreCase(directory[i])) {
inDir = true;
break;
}
}
return inDir;
}
Капеллер, может быть, эта программа вам поможет. Я разработал эту программу, используя новый java.nio api. Взгляни :). Внесите необходимые изменения в соответствии с вашими потребностями.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.LinkedHashSet;
import static java.lang.System.*;
public final class NameSearcher{
private String sourceFile;
private final Collection <String> fileContent = new LinkedHashSet<>();
private Thread EXISTENCE_WATCHER = null;
private Path sourcePath = null;
public String getSourceFile(){ return this.sourceFile; }
public void setSourceFile(final String value){
this.sourceFile = value;
sourcePath = Paths.get(sourceFile);
if(Files.exists(sourcePath,LinkOption.NOFOLLOW_LINKS)){
//Setting up the file watcher thread !!!
EXISTENCE_WATCHER = new Thread(()->{
try{
if(!Files.exists(sourcePath,LinkOption.NOFOLLOW_LINKS)) {
EXISTENCE_WATCHER.join();
System.exit(-2);
}
Thread.sleep(5000);
}catch(InterruptedException cause){ cause.printStackTrace();}
});
//Reading from the file
try(Scanner reader = new Scanner(sourcePath.toFile())){
while(reader.hasNext()) fileContent.add(reader.next());
}catch(IOException cause){cause.printStackTrace();}
}else{
out.println("Sorry, the specified source file cannot be found !!!. Program exits now !!!");
System.exit(-1);
}
}
public Boolean contains(final String key){
return fileContent.contains(key);
}
public void addName(final String name){
if(!fileContent.contains(name))
fileContent.add(name);
}
public Boolean deleteName(final String name){
return fileContent.remove(name);
}
@Override
public void finalize(){
out.println("\nInvoked finalization ....");
out.println("\nFile Buffer up on finalize entry");
fileContent.stream().forEach(out::println);
out.println("--------------------------------");
try( PrintWriter writer = new PrintWriter(new FileOutputStream(sourcePath.toFile()));
Scanner comparisonReader = new Scanner(sourcePath.toFile());
){
while(comparisonReader.hasNext()){
String file_token = comparisonReader.next();
if(fileContent.contains(file_token)) fileContent.remove(file_token);
}
fileContent.parallelStream().forEachOrdered(token -> {writer.append(token); writer.println(); out.println("Elem -> "+token);});
}catch(IOException cause){
cause.printStackTrace();
}finally{
if(EXISTENCE_WATCHER.isAlive()){
try{
EXISTENCE_WATCHER.join();
}catch(Exception cause){ cause.printStackTrace();}
}
fileContent.clear();
sourcePath = null;
}
}
public static void main(String[] args) {
NameSearcher obj = new NameSearcher();
obj.setSourceFile("test.txt");
out.printf("Contains check for Line1 : %b",obj.contains("Line1"));
obj.addName("Jai");
obj.addName("Matha");
obj.finalize();
}
}
inDirectory
, но другие методы по-прежнему имеют ту же проблему ( исключение NullPointerException при поиске в текстовом файле ).