1

This program takes in input the "hello my name is bob" and spits it out backwards. I really need help making it that the program reads in a text file and spits out the text file backwards. Thanks in advance!

public class Recursion
{
 public static void main(String[] args) throws FileNotFoundException {
 System.out.println(printBackwards("hello my name is bob")); 
}



public static String printBackwards(String s){
 if(s.length() <= 1)
        return s;
    else 
        return printBackwards(s.substring(1,s.length()))+s.charAt(0);
  }
}
user6904265
  • 1,938
  • 1
  • 16
  • 21
jim
  • 11
  • 2
  • I imagine this is homework, but this is a one line solution (not using recursion) Reads 'input.txt': `System.out.println(new StringBuilder(new Scanner(new File("input.txt")).useDelimiter("\\Z").next()).reverse());` – d.j.brown Nov 14 '16 at 23:44
  • 1
    Possible duplicate of [Whats the best way to recursively reverse a string in Java?](http://stackoverflow.com/questions/859562/whats-the-best-way-to-recursively-reverse-a-string-in-java) – Hypino Nov 14 '16 at 23:50
  • @Hypino if you look the code posted by OP you should see that he has already implemented the "reverse string metod".. He just ask how to read/write the input/output from/into a file. – user6904265 Nov 14 '16 at 23:57
  • @user6904265 Oh yeah, my mistake. Possible duplicate of [How do I create a Java string from the contents of a file?](http://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file) – Hypino Nov 15 '16 at 00:00
  • @Hypino ok, yes but he asks also how to write the reversed string on a output file. – user6904265 Nov 15 '16 at 00:03
  • @jim have you solved or you still need help? A feedback is appreciated. ty – user6904265 Nov 15 '16 at 00:51
  • @user6904265 got it thanks guys! I'll drop some feedbac. Thanks ty – jim Nov 15 '16 at 02:24

3 Answers3

0

Based on the comments for the question, this will read a file called input.txt and save it to a new file called output.txt using your method for reversing a String.

All lines in input.txt are firstly added to a List.

The List is then iterated through backwards from the last element, and with each iteration the reversed String written to output.txt.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;

public class Example {

    public static void main(String[] args) throws IOException {    
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            Scanner scanner = new Scanner(new File("input.txt"));
            List<String> fileContents = new ArrayList<>();
            while (scanner.hasNextLine()) {
                fileContents.add(scanner.nextLine());
            }
            ListIterator<String> it = fileContents.listIterator(fileContents.size());
            while (it.hasPrevious()) {
                writer.write(printBackwards(it.previous()));
                writer.newLine();
            }
        }
    }

    public static String printBackwards(String s) {
        if (s.length() <= 1) {
            return s;
        } else {
            return printBackwards(s.substring(1, s.length())) + s.charAt(0);
        }
    }
}

If however you just want to display it to the standard output, you can adjust it to the following:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;

public class Example {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("input.txt"));
        List<String> fileContents = new ArrayList<>();
        while (scanner.hasNextLine()) {
            fileContents.add(scanner.nextLine());
        }
        ListIterator<String> it = fileContents.listIterator(fileContents.size());
        while (it.hasPrevious()) {
            System.out.println(printBackwards(it.previous()));
        }
    }

    public static String printBackwards(String s) {
        if (s.length() <= 1) {
            return s;
        } else {
            return printBackwards(s.substring(1, s.length())) + s.charAt(0);
        }
    }
}

Or as I said in my comment earlier, you can just read the whole file in one go and reverse it:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Example {

    public static void main(String[] args) throws FileNotFoundException {
        System.out.println(printBackwards(new Scanner(new File("file.txt")).useDelimiter("\\Z").next()));
    }

    public static String printBackwards(String s) {
        if (s.length() <= 1) {
            return s;
        } else {
            return printBackwards(s.substring(1, s.length())) + s.charAt(0);
        }
    }
}
d.j.brown
  • 1,822
  • 1
  • 12
  • 14
-1

This should work as you expect. I assume that in the filename_in.txt you have only one line, otherwise you have to loop (I let you to do this as exercise):

public static void main(String[] args){
       Scanner in = null; 
       PrintWriter writer = null;
       try{
           in = new Scanner(new FileReader("filename_in.txt"));
           writer = new PrintWriter("filename_out.txt");
           writer.println(printBackwards(in.nextLine()));
        } catch (Exception e) {
           e.printStackTrace();
        }
       finally {
           in.close(); 
           writer.close();
       }
    }
user6904265
  • 1,938
  • 1
  • 16
  • 21
-1

Use this code to get the string that you want to reverse from a text file:

try{
    String myString;
    BufferedReader input = new BufferedReader(new FileReader("Filepath.txt");
    while((myString = input.readLine()) != null){}
}
catch(FileNotFoundException ex){
    //Error Handler Here
}
catch(IOException ex){
    //Error Handler Here
} finally {
    try{
        if(br != null) br.close();
    }
    catch(IOException ex){
        ex.printStackTrace();
    }
}

Don't forget to import:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException
William Lin
  • 131
  • 2
  • 8