Amerul Atiq
Amerul Atiq

Reputation: 51

Java - Naming a file in FileWriter using Scanner

How do I name a file using Scanner? For some reason, Java's FileWriter won't accept a pre-defined String as an input. The code below is simplified to what I mean : `

import java.io.*;

public class Example{
    public static void main(String[] arg) {
        String title;
        Scanner input = new Scanner(System.in);

        title = input.next();
        try {
            FileWriter fw = new Filewriter(title);
        } catch (IOException ex) {}
        input.close()
    }
}

I don't know why it doesn't work. I've checked other questions online and none of them seem to help.

EDIT: Okay, I edited the IOException and here's what I got from the stack trace;

java.io.FileNotFoundException: entries\awdwad
.txt (The filename, directory name, or volume label syntax is incorrect)
    at java.base/java.io.FileOutputStream.open0(Native Method)
    at java.base/java.io.FileOutputStream.open(FileOutputStream.java:292)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:235)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:156)
    at java.base/java.io.FileWriter.<init>(FileWriter.java:82)
    at main.JournalInput.main(JournalInput.java:26)

I'm sorry, I'm still confused about this.

EDIT EDIT: I found out the problem. There was a Delimiter I forgot and removing it apparently fixed it. I didn't put it in the code above either. Sorry for wasting everyone's time on this.

Upvotes: 2

Views: 287

Answers (2)

Afsar Ahamad
Afsar Ahamad

Reputation: 1997

Mostly depends of your input to scanner for example if you will pass filename along with / then it won't work. Posting same code tested on three different inputs.
1. example
2. example.txt
3. /example.txt

public class Example {


     public static void main(String[] arg) {
            String title;
            Scanner input = new Scanner(System.in);

            title = input.next();
            try {
                FileWriter fw = new FileWriter(title);
                System.out.print("Working with "+title);

            } catch (IOException ex) {
                System.out.print("Error: with "+ex);
                ex.printStackTrace(System.out);
            }
            input.close();
        }

}

will work on first two input but will throw exception in case of last input.

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109557

Scanner parses text into tokens, x.txt will easily become 3 tokens. Instead of next() use nextLine(). Still better would be to not use Scanner.

A FileNotFoundException under Windows also happens a lot, when the file extension is hidden (.txt, .docx, ...).

Upvotes: 1

Related Questions