如何创建一个txt文件,其名称来自用户输入

时间:2014-04-04 07:59:13

标签: java file-io

我想创建一个txt文件并将其存储在特定位置,例如C:\或C:\ Users。此外,我希望用户输入文件的名称作为输入。我已尝试使用下面的代码,但它永远不会有效。

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

public class cITF implements ICommand{

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

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a file name");
        String 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");
        }
    }

}

其中CurrentpathcShell类的成员,等同于C:\(保存txt文件的目录)。当它运行时,它输出“文件创建”,虽然没有创建。

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("ls", new cLS());
    myhashData.put("gd", new cGD());
    myhashData.put("md", new cMD());
    myhashData.put("rnd", new cRND());
    myhashData.put("del", new cDEL());
    myhashData.put("hd", new cHD());
    myhashData.put("uhd", new cUHD());
    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");
            }
    }
}

3 个答案:

答案 0 :(得分:0)

我建议首先尝试一些你肯定有访问权限的目录并打印文件路径。然后,您可以检查文件是否通常由您的代码创建。

public static void main(final String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a file name");
    String filename = scan.nextLine();
    try
    {
        File file = new File("/tmp", filename);
        System.out.println("path=" + file.getAbsolutePath());
        file.createNewFile();
        System.out.println("File created");
    }
    catch(Exception e)
    {
        e.printStackTrace();
        System.out.println("Failed to create file");
    }
}

答案 1 :(得分:0)

编辑:以下答案不反映原始问题。请忽略,接受评论。

public static void main(String[] args) {
    // open filechooser at user's current location (this will be in your
    // eclipse workspace if running from eclipse (/NetBeans)
    JFileChooser jfc = new JFileChooser(System.getProperty("user.dir"));
    // just for safety; we're saving files anyhow
    jfc.setMultiSelectionEnabled(false);
    jfc.setDialogTitle("Enter file name and select location . .");
    // null should be the name of the parent JFrame
    int returnVal = jfc.showSaveDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
        String path = jfc.getSelectedFile().getAbsolutePath();
        writeToCustomFile(path);
    }
}

public static void writeToCustomFile(String path) {
    File f = new File(path);
    // redundancy check, feel free to remove
    if(!f.getPath().equals("")) {
        // create parent directories if they don't exist
        f.getParentFile().mkdirs();
        try {
            f.createNewFile();
            System.out.println("File created");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Failed to create file");
        }
    }
}

答案 2 :(得分:0)

答案很简单。

您可能正在使用计算机上运行的Windows Vista或最新操作系统。 Windows doesn't allow you to create files in C:\ folder [root]

You can keep some other drive [D:\ or E:\ or C:\somefolder] other than System Related folders它将完美无瑕地运作。 这是一个操作系统限制,以避免恶意软件/安全相关的问题