【发布时间】: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");
}
}
}
其中Currentpath 是cShell 类的成员,相当于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 的值是多少?这条路存在吗?