-1

What is wrong with my coding? I tried to create a file name & printout in the text file package practical12;

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

   public class q4 {
    public static void main (String []args) throws FileNotFoundException{
System.out.println("please input file name");

String name;
//take file name
Scanner in;
in = new Scanner(System.in);
name = in.nextLine();
PrintWriter out = new PrintWriter(name);
    // create textfile
out.println("Hello! My first program in File");
// write the text
out.close();
    //close the file
}
}
Chris Park
  • 13
  • 3

2 Answers2

1

If you just entered the name of the file instead of absolute path, then it will be created in current working directory of your program. In order to check current working directory using java please check Getting the Current Working Directory in Java

Community
  • 1
  • 1
-2

When you give the file name to the program there must be .txt or something else in the end. If there is not fileWriter cannot create a file and throws an error. If you want to make sure the program does dot crash here is an example.

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

   public class q4 {
   public static void main (String []args) throws FileNotFoundException{
System.out.println("please input file name");

String name;
//take file name
Scanner in;
in = new Scanner(System.in);
name = in.nextLine();
PrintWriter out = new PrintWriter(name+".txt");
// create textfile
out.println("Hello! My first program in File");
// write the text
out.close();
//close the file
}
}
OAJJ
  • 35
  • 7