Is there any simple way to create a txt file with its name come from the user input. Also the file will be stored in a specific location such as C:\Users for example. Here is what I do but doesn't work.

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

public class cITF implements ICommand{


    public void Execute() {
    // TODO Auto-generated method stub

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a file name");
        filename = scan.nextLine();

        try
        {
            File file = new File(cShell.Currentpath, filename);
            file.createNewFile();

            System.out.println("File created");

        }
        catch(Exception e)
        {
            System.out.println("Failed to create file");
        }
    }


}

I also have another class cShell which consist of the Currentpath (C:).

import java.util.HashMap;
import java.util.Scanner;


    public class cShell {

        static String Currentpath="C:\\";
        public String Current = Currentpath;

        static HashMap<String, ICommand> myhashData=new HashMap<String, ICommand>();

        public static void main(String[] args)
        {


            myhashData.put("ltf", new cITF());
            myhashData.put("nbc", new cNBC());
            myhashData.put("gdb", new cGDB());
            myhashData.put("Tedit", new cTedit());


            System.out.print(Currentpath+"> ");

            Scanner scan = new Scanner(System.in);
            String Input = scan.nextLine();



            if(myhashData.containsKey(Input))
            {
                ICommand myCommand=myhashData.get(Input);
                myCommand.Execute();
            }
            else
            {
                System.out.println("Invalid Command");
            }
           }
}

*ICommand is an interface.

Dani AI

Generated

Brief summary and practical fixes for the behavior seen in this thread.

As discovered by , the problem was related to how the path was formed and where the program attempted to write. Common causes are incorrect path assembly (missing separators or unescaped backslashes), trying to create a file in a location without write permission (for example the OS root on modern Windows), or swallowing the exception so the real error is hidden. was right to recommend logging the exception; ’s suggestion about an output stream only applies when you want to write data, not simply create an empty file.

Safer, more robust approach (use java.nio.file when possible):

import java.nio.file.*;

Path dir = Paths.get(System.getProperty("user.home"));        // writable location
Files.createDirectories(dir);                                 // ensure folder exists
Path file = dir.resolve(filename + ".txt");
Files.createFile(file);                                       // throws if it cannot create

This avoids hand-assembling separators and makes intent clear. For older Java, use new File(parent, child) or File.separator rather than concatenating backslashes in string literals.

Troubleshooting checklist

  • Print the absolute path before creating (file.toAbsolutePath() or file.getAbsolutePath()), and log the exception stack trace so the real cause (permission denied, invalid name, existing file, etc.) is visible.
  • Remember Windows reserved names (CON, PRN, AUX, NUL, COM1..COM9, LPT1..LPT9) and illegal characters.
  • Writing to C:\ may require elevated privileges; prefer a user-writable folder (System.getProperty("user.home") or a subfolder under Users).
  • Use Files.write/Files.writeString (or a try-with-resources stream) when you need to add text immediately after creating the file.

These steps explain why the path-change fixed the symptom and show safer, future-proof ways to create files.

Recommended Answers

All 7 Replies

yes there is a way to do that.

Any wrong with my code..?? why can't it do it..

Any suggestions..?

You declared a new File but you also have to declare an ObjectOutputStream (TextOutputStream) in order to save it on your desktop.

Try that?

"It doesn't work" tells us nothing. Did you get an exception? Was the file created but with the wrong location and/or name? Etc?
The exception on line 22 (catch) contains details of any errors. It is a bad mistake not to use that. Add an e.printStackTrace(); inside the catch clause to see the full error message.

Declaring an output stream will not affect the creation of a new file when you use createNewFile(), so that's not the problem.

Print the values of cShell.Currentpath and filename just after line 16 to confirm that they are what you expected.

First of all, thank you for you replies...I have just recently solved it and it's something wrong with how I define the path to save the file. I tried File file = new File(cShell.Currentpath+"\"+filename); and it works. I also found out that it cannot works in the C: itself but I have to run it inside another directory for example C:\Users

OK! Thanks for sharing the solution with us. Please mark this "solved" for our knowledge base.

J

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.