1

I need to rename the file temp.txt later on in my code. I tried doing this with the newFile = new File(name); line, but this just created a new file entirely. Could you point me in the right direction here?

public static File InputOutput (Scanner console, int in_Out) throws
        FileNotFoundException {
    //<editor-fold>
    String name = "newName";
    String line = "";
    String in_OutText = "";
    File newFile = new File("temp.txt");
    for (int i = 0; i <= in_Out; i++) {
        if (i == 0) {
            in_OutText = "Input";
        } else {
            in_OutText = "Output";
        }
        System.out.print(in_OutText + " file name: ");
        name = console.next();
        if (i == 1) {
            newFile = new File(name);
        }
    }
    PrintStream inputCopy = new PrintStream(newFile)
    Scanner input = new Scanner(name);
    while (input.hasNextLine()) {
        line = input.nextLine();
        inputCopy.println(line);
        inputCopy.println("WORKED");
    }
    return newFile;
}

Thanks!

  • 1
    Java's file class has a renameTo method : https://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo(java.io.File) Generally I would recommend using the java.nio.file API because it is nicer to work with (e.g. clearer Exceptions and not methods returning a boolean value). Here are different ways to accomplish this : http://www.baeldung.com/java-how-to-rename-or-move-a-file – Don Nov 17 '17 at 20:40
  • Thank you, but I am only allowed to use scanners to do this. Maybe I just need to re-assess my process for completing this assignment and start over again. – Molly Taylor Nov 17 '17 at 21:09

0 Answers0