Home > Software engineering >  write a program in it that reverses each line in a file
write a program in it that reverses each line in a file

Time:10-21

Trying to reverse a file line by line

public static void main(String[] args) throws FileNotFoundException {

    System.out.println("filname: ");
    Scanner input = new Scanner(System.in);
    String filnamn = input.nextLine();
    File file = new File(filnamn);
    Scanner inputFile = new Scanner(file);

    PrintWriter writer = new PrintWriter(file);

    while (input.hasNextLine()) {
        String fil = input.next();
        int reverse = 0;
        for (int i = fil.length(); i >= 0; i--) {
            reverse = reverse   fil.charAt(i);
            writer.print(reverse);
        }

    }
    inputFile.close();
    writer.close();
    input.close();

When trying to reverse my file it just get erased instead of it being backwards

CodePudding user response:

You have an issue with the path of file. You can extract the full path by -

System.out.println("filname: ");
    Scanner input = new Scanner(System.in);
    String filnamn = input.nextLine();
    
    // Add this
    final String fullPath = <YOUR_CLASS>.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    
    // Then correct the path
    File file = new File(fullPath_filnamn);
    Scanner inputFile = new Scanner(file);

    PrintWriter writer = new PrintWriter(file);

    while (input.hasNextLine()) {
        String fil = input.next();
        int reverse = 0;
        for (int i = fil.length(); i >= 0; i--) {
            reverse = reverse   fil.charAt(i);
            writer.print(reverse);
        }

    }
    inputFile.close();
    writer.close();
    input.close();

CodePudding user response:

You are not reading the file at all, but instead input (console). That means your program is waiting for you to enter text. Also your file gets deleted since you are trying to write to it.

Switch your while loop to read from inputFile instead of input.

Remove the line, or come up with a different output file:

PrintWriter writer = new PrintWriter(file);
  • Related