【问题标题】:How do I create a txt file with its name coming from a user input如何创建名称来自用户输入的 txt 文件
【发布时间】:2014-04-04 07:59:13
【问题描述】:

我想创建一个 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");
            }
    }
}

【问题讨论】:

  • 尝试在系统输出中打印完整的文件名,看看会发生什么
  • @vishram0709 为什么?控制台输入有什么问题?
  • @zencv 你的全名是什么意思..??我应该删除路径并只放置文件名..??
  • 对不起,伙计们,当我运行它时,它给了我“无法创建文件”而不是“创建文件”,正如我上面提到的......知道为什么文件没有在目录 cShell 中创建。当前路径..??
  • cShell.Currentpath 的值是多少?这条路存在吗?

标签: java file-io


【解决方案1】:

我建议先尝试一些您绝对可以访问并打印文件路径的目录。然后您可以检查文件是否是由您的代码创建的。

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");
    }
}

【讨论】:

  • 我认为如果我输入 C:\ 而不是 cShell.Currentpath ... 说如果我输入 C:\\sample.txt 而不是提供用户输入,那么文件创建成功...但这不是我想要的..我希望用户提供文件名..
【解决方案2】:

编辑:下面的答案不反映原始问题。请无视,带到cmets。

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");
        }
    }
}

【讨论】:

  • 我的情况有点不同。我的程序应该像命令提示符一样工作,用户应该输入一些命令,比如让我们说 "lft sample.txt" ,程序应该在 cShell.Currentpath 中给出的目录中创建一个名为 sample.txt 的文件
  • 啊,对不起。我不知道你的 cShell 类是做什么的,我在 Google 上也找不到。您能否提供代码的完整工作示例?
【解决方案3】:

答案很简单。

您可能正在使用 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 它将完美运行。 这是避免恶意软件/安全相关问题的操作系统限制

【讨论】:

  • @user3483389,Windows 7 和最新版本的 Windows 永远不可能。现在才测试。顺便说一句,创建文件和文件夹是不同的。
  • Reddy,如果是权限问题,他会得到java.io.IOException: Access is denied / "Failed to create file"。他正在“创建文件”。
  • 任何简单的方法来做到这一点..??我认为它非常简单,但我还没有解决它......
  • @user3483389,如果有的话,您是否更改了任何其他硬盘分区的路径,或者将其更改为您的用户文件夹(C:\users\您的用户名)
猜你喜欢
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多