我唯一的问题是我在评论中出现错误。我愿意将索引1处的字符串(token [])数据发送到主目录中的Createnewfile()方法。我做不到请指导我该怎么做。
import java.util.*;
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main( String[] args )
{
Scanner S = new Scanner (System.in);
System.out.println ("FileExplorer");
System.out.println ("Select:");
System.out.println ("1.create new file");
System.out.println("2. Enter text in the new created file ");
System.out.println ("3.View List");
System.out.println ("4.Display contents of particular file");
System.out.println ("5.Delete a selected file");
System.out.println ("6.Copy files to other directory");
System.out.println ("7.Cut files from one directory to other");
System.out.println ("My File Explorer:");
String phrase = S.nextLine();
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
for (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);
if (tokens[0].equals ( "createfile") )
{
System.out.println ("Create");
Createnewfile( tokens[] ); //I get an error here, please tell me how to send
//the tokens[1] index 1 string to my createnewfile function
}
if (tokens[0].equals ( "entertext") )
{
System.out.println ("entering text");
String St = tokens[1];
Entertext(St);
}
if (tokens[0].equals ( "showcontent") )
{
System.out.println ("Displaying contents");
}
if (tokens[0].equals ( "List") )
{
System.out.println ("Listing all .txt files");
}
if (tokens[0].equals ( "delete") )
{
System.out.println ("Deleting the selected file");
}
}
public void Createnewfile( String [] tokens)
{
try
{
File file = new File(tokens[1]);
if (file.createNewFile())
{
System.out.println("File is created!");
}
else
{
System.out.println("File already exists.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void Entertext(String St)
{
try
{
Scanner S = new Scanner (System.in);
String content = S.nextLine();
File file = new File( St);
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
最佳答案
如果您要尝试使用数组引用,只需丢失[]
即可:
Createnewfile(tokens);
但是,这不只是通过
tokens[1]
。奇怪的是,您的
Createnewfile
方法始终使用tokens[1]
-该方法具有String
参数(而不是String[]
)更有意义,然后可以将其称为:Createnewfile(tokens[1]);
仅传递对要用于创建文件的字符串的引用-例如,就像您对
Entertext
方法所做的那样。我也强烈建议您学习并遵循Java中的命名约定。 (因此您的方法将是
createNewFile
,enterText
等。)