Question: I'm having some trouble with my code. In particular, it adds elements to a text file fine, but when removing elements i'm attempting to make
I'm having some trouble with my code. In particular, it adds elements to a text file fine, but when removing elements i'm attempting to make a temp file, delete the original file, and rename the temp file to the original name. I cannot get it to delete the original file. Please advise, code posted below.
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
public class RankingourFavorites {
static String filepath = "I:\\favegames2.txt";
public static void main(String[] args) throws Exception {
Scanner scan2 = new Scanner (System.in);
BufferedReader reader = new BufferedReader(new FileReader("I:\\favegames2.txt"));
String line;
try {
while ((line = reader.readLine()) != null ) {
line = line.trim();
if (!line.isEmpty()){
System.out.println(line);
}
}
}
catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
addMoreElements();
ArrayList
ArrayList
BufferedReader buff;
try{
buff = new BufferedReader(new FileReader("I:\\favegames2.txt"));
} catch(Exception ehhhh){
throw ehhhh;
}
String elementToBeRemoved = new String();
String keepRunning = new String();
while(!keepRunning.equalsIgnoreCase("-1")) {
System.out.println("Please enter an element to be removed. Enter -1 to stop removing elements.");
keepRunning = scan2.nextLine();
if(elementToBeRemoved == "-1") {
break;
}
elementToBeRemoved = keepRunning;
removeElements(filepath,elementToBeRemoved);
}
readElementsToArrayListAndPrint(buff, listelements);
ArrayList
for (int i = 0; i < listelements.size(); i++){
itemsranked.add("");
}
ArrayList
for (int i = 0; i < listelements.size(); i++){
elementComments.add("");
}
Scanner scanning = new Scanner(System.in);
//Main Loop
for (int i = 0; i < listelements.size(); i++){
System.out.println("#" + (i+1) + ": " + listelements.get(i));
//Collect comment.
System.out.println("Please write any comments you have about this game!");
String comment;
try {
comment = scanning.nextLine();
} catch (Exception e2) {
comment = "No comment.";
}
//Collect Rank
int rank = -1;
while (rank == -1) {
System.out.println("How would you like to rank this element?");
try {
rank = scanning.nextInt();
if (!makesSense(rank, listelements.size()+1)){
rank = -1;
System.out.println("Please enter an integer that is between 1 and "+ listelements.size() + ".");
}
else {
rank--;
}
} catch (Exception e) {
System.out.println("Please enter a valid integer input.");
scanning.nextLine();
}
scanning.nextLine();
}
if (itemsranked.get(rank) == ""){ //Rank was unoccupied
System.out.println("Rank accepted without incident!");
placeElementAtLocation(rank, listelements.get(i), comment, itemsranked, elementComments);
} else { //Rank was occupied
System.out.print("Rank already in use...");
if (pushelementDown(rank, itemsranked, elementComments)){ //Elements can/were pushed
System.out.println("Elements at rank " + (rank+1) + " were pushed "
+ "down to accommodate the current element.");
placeElementAtLocation(rank, listelements.get(i), comment, itemsranked, elementComments);
} else { //Elements could not be pushed
System.out.println("Elements beyond rank " + (rank+1) + " were all taken. "
+ "Placing element at next lowest rank above " + (rank+1) + ".");
placeElementAtLowestRank(rank, listelements.get(i), comment, itemsranked, elementComments);
}
}
}
scanning.close();
//Display results
System.out.println("Results!");
for(int i = 0; i < itemsranked.size(); i++){
System.out.println("'" + itemsranked.get(i) + "' | " + (i+1) + " | " + elementComments.get(i));
}
//Bye
System.out.println("Thanks for running me! Enjoy!");
}
public static void readElementsToArrayListAndPrint(BufferedReader reader, ArrayList
String element = "";
try {
element = reader.readLine();
} catch (IOException e) {
System.out.println("Oops! Something went wrong!");
e.printStackTrace();
}
while (element != null) {
element = element.trim();
listelements.add(element);
if (element.isEmpty())
System.out.println(element);
try {
element = reader.readLine();
} catch (IOException e) {
System.out.println("Oops! There was an Error!");
e.printStackTrace();
}
}
try {
reader.close();
} catch (IOException e) {
System.out.println("Oops! There was an Error!");
e.printStackTrace();
}
}
public static boolean pushelementDown(int rank, ArrayList
int i = rank;
for (; i < ranked.size() ; i++){
if (ranked.get(i) == ""){
break;
}
}
if (i == ranked.size()){
return false;
} else {
ranked.remove(i);
usercomments.remove(i);
ranked.add(rank, "");
usercomments.add(rank, "");
return true;
}
}
public static void placeElementAtLocation(int loc, String element, String comment, ArrayList
ranked.set(loc, element);
usercomments.set(loc, comment);
}
public static void placeElementAtLowestRank(int loc, String element, String comment, ArrayList
for(loc--; loc >= 0; loc--){
if(ranked.get(loc) == ""){
ranked.set(loc, element);
usercomments.set(loc, comment);
System.out.println("Element was placed at rank " + (loc+1) + ".");
break;
}
}
}
public static void addMoreElements() throws IOException{
Scanner scan = new Scanner(System.in);
Scanner sch = new Scanner(System.in);
String YorN;
String s = "";
while (true) {System.out.println("Do you want to add an element? Y for yes or N for No");
YorN = sch.next();
if (YorN.equalsIgnoreCase("Y")) {
System.out.println("Please input your desired element");
s = s + scan.nextLine();
}else if (YorN.equalsIgnoreCase("N")) {
System.out.println("Are you finished adding elements? Y for yes and N for No(or any other key) ");
char c = sch.next().charAt(0);
if(c == 'Y' || c == 'y'){
overWriteElements(s);
break;
}
}
}
}
public static boolean makesSense(int userinp, int size){
if (userinp > 0 && userinp < size){
return true;
}
return false;
}
public static void overWriteElements(String s) throws IOException{
BufferedWriter bw = new BufferedWriter(new FileWriter(filepath, true));
bw.write(" "+s);
bw.close();
}
public static void removeElements(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line ;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
br.close();
pw.close();
//inFile.delete(); This is being done in the if statement below
//Delete the original file
if (inFile.delete()) {
System.out.println("File deleted successfully.");
}else {
System.out.println("File could not be deleted.");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/** public static void deleteElem(int loc, int listelements){
for(int i=0; i if(listelements.get(i).equalsIgnoreCase(ElementToBeDeleted){ listelements.remove(i); comments.remove(i); // each index in comments with coincide with elements } } } **/ }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
