Я относительно знаю Java, и для личного проекта я пытаюсь написать программу, которая может принимать пользовательский ввод для записи в текстовый файл и удалять текст из строка (указана индексом массива) из массива, построенного из того же текстового файла, так что когда вы распечатываете содержимое файла, удаляемое вами действительно удаляется.Удаление текста из массива, сделанного из файла на Java
Вот мой код, я извиняюсь за любые другие ошибки, которые я не могу видеть:
public class Writing {
Scanner input = new Scanner(System.in);
File customerFile = new File("Customers.txt");
String[] fileArray;
public Writing() throws IOException{
FileReader fileReader = new FileReader(customerFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
fileArray = lines.toArray(new String[lines.size()]);
}
public void FileWrite() throws IOException {
String inputData = input.nextLine();
if (!customerFile.exists()) {
customerFile.createNewFile();
}
FileWriter fileWriter = new FileWriter(customerFile.getName(),true);
BufferedWriter bufferWriter = new BufferedWriter(fileWriter);
bufferWriter.write(inputData + "\n");
bufferWriter.close();
System.out.println("Done.");
}
//Here is the one I have trouble with
public void RemoveFile() throws IOException {
LinkedList<String> cusList = new LinkedList<String>(Arrays.asList(fileArray));
System.out.println("Which one would you like to delete? [0-#].");
//then it prints the list so you can see what you want to delete
for(String x: cusList){
System.out.println(x);
}
String removeThis = input.nextLine();
int removeNum = Integer.parseInt(removeThis);
if()){ //if the user input contains the number that occurs as an index in the list
//not sure what to put here
fileArray = cusList.toArray(fileArray);
}else{
System.out.println("Remove failed.");
}
}
}
я застрял, потому что, несмотря на других прошлые попытки решить эту проблему, я в конечном итоге получить свое другое заявление или без каких-либо изменений в текстовый файл.
EDIT: Вот основные попытки, которые я предпринял для решения этой проблемы, но безрезультатно. Это класс RemoveFile().
Failed Метод:
//tries to remove the element if it is found, before I decided to jusr remove the index
//example: if "Cocoa Powder" is typed in and it exists within the list of the array created from the file, remove it.
if(cusList.contains(removeThis)){
cusList.remove(removeThis);
cusList.toArray(fileArray);
}
//the else statement here saying that it failed
Failed Метод 2:
//attempts to remove the content of the inputted index within the list
if(removeNum.equals(cusList.indexOf(removeNum))){
cusList.remove(removeNum);
cusList.toArray(fileArray);
}
//else statement would go here
Помощь!
Решение: Я понял это, спасибо всем, которые внесли свой вклад, чтобы помочь, и я понял, что простое решение, чтобы очистить все содержимое текстового файла с массивом из со всего содержимого , а затем записывая это содержимое обратно в текстовый файл после всех изменений. Вот мой код:
// RemoveFile method
public void RemoveFile() throws IOException {
LinkedList<String> cusList = new LinkedList<String>(
Arrays.asList(fileArray));
System.out.println("Which one would you like to delete? Each customer is given a number [1-#].");
System.out.println("The file will change when program terminated.");
for (int i = 1; i < fileArray.length; i++) {
for (String x : cusList) {
System.out.println("Customer " + i + ": " + x);
i++;
}
}
String removeThis = input.nextLine();
int removedNum = Integer.parseInt(removeThis);
int removeNum = removedNum - 1;
if (removeNum >= 0 && removeNum < cusList.size()) {
cusList.remove(removeNum);
fileArray = cusList.toArray(fileArray);
PrintWriter writer = new PrintWriter(customerFile);
writer.print("");// clears the file contents
writer.close();
FileWriter fileWriter = new FileWriter(customerFile.getName(), true);
BufferedWriter bufferWriter = new BufferedWriter(fileWriter);
for (String x : cusList) {
bufferWriter.write(x + "\n");
}
bufferWriter.close();
} else {
System.out.println("Index out of bounds, " + removeNum + " >= "
+ cusList.size());
}
Это, казалось, работало прекрасно и предложение MadProgrammer сделал логическую работу, вместо того, чтобы постоянно возвращаются ложные, а затем программа позволяющая извлечь данные из файла в массив, очистить содержимое массив, а затем записать его обратно в файл.
Как вы писали, вы сами предприняли несколько попыток, прежде чем публиковать этот вопрос. Не могли бы вы сказать об этом? Что вы пытались включить в условие if, и как вы пытались удалить строку? Ваш вопрос был бы гораздо более ценным, если бы мы знали, с кем вы боретесь, вместо того, чтобы просто дать ответ, который работает. –
Хорошо, я сделал изменения. Извините, скорее, новичок в задании таких вопросов. –