我的代码用于在目录的文件夹中创建文件,该文件根据用户输入的内容在顶部包含标题。
import java.util.*;
import java.text.*;
import java.io.*;
public class setup {
public static void main(String[] args) {
Scanner userin = new Scanner(System.in);
int hwnum;
String hwsummary;
int period;
String name;
System.out.println("Enter name: ");
name = userin.next();
System.out.println("Enter APCS period: ");
period = userin.nextInt();
System.out.print("Enter HW number: ");
hwnum = userin.nextInt();
System.out.println("Enter HW summary: ");
hwsummary = userin.next();
System.out.println("Enter file name: ");
String hwname = userin.next();
hwname = hwname + ".java";
new File("/hw" + hwnum).mkdirs();
new File("/hw" + hwnum +"/" + hwname);
String filename;
filename = "\\hw" + hwnum + "\\" + hwname;
System.out.println("/*");
System.out.println(name);
System.out.println("APCS1 " + "pd" + period);
System.out.println("HW" + hwnum + " -- " + hwsummary);
System.out.println(getdate());
System.out.println("*/");
}
public static String getdate() {
DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String todaydate;
todaydate = dateformat.format(date);
return todaydate;
}
}
代码的最终结果,如果由用户提供,则应该是名为" / hwxx"的目录中的java文件。并且应该有类似的标题:
/*
Name
APCS1 pdx
HW# - HWSUMMARY
DATE
*/
答案 0 :(得分:0)
System.out.println()
无法用于写入文件,只能将文本打印到标准输出流。可以使用FileWriter和BufferedWriter来写入文件。尝试用以下方法替换main方法的最后一部分:
try {
FileWriter outputStream = new FileWriter(filename);
try (BufferedWriter out = new BufferedWriter(outputStream)) {
out.write("/*");
out.newLine();
out.write(name);
out.newLine();
out.write("APCS1 pd" + period);
out.newLine();
out.write("HW" + hwnum + " -- " + hwsummary);
out.newLine();
out.write(getdate());
out.newLine();
out.write("*/");
}
} catch (IOException ex) {
// some sort of error message here
// this block will only be run if the program is unable to create or write to the specified file
}
请注意,write()
方法的文件写入等同于print()
而不是println()
,因此必须在每个方法之间包含newline()
方法文本行,以避免将它们全部写入同一行文本。但是,更短且更乏味的替代方法是将字符串"\n"
(换行符)添加到写入文件的每一行的末尾,如下所示:
out.write("/*\n");
out.write(name + "\n");
//etc.
如果您选择以这种方式执行此操作并最终将所有文本写入一行(如果您正在运行Windows则是一个常见问题),请使用"\r\n"
而不是{{1 }}