我的代码有什么问题? [英] What wrong with my code?
本文介绍了我的代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个程序,它将创建一个文本文件并编写hello world
如果程序在文本文件应包含2个hello world的同一天运行两次,并且如果它运行在同一天但不同的月份它应该删除现有的书面文字并写下另一个你好的世界;
我尝试了什么:
i am creating a program that will create a text file and write hello world
if the program is run twice on the same day the textfile should contain 2 hello world and if it is run on the same day but different month it should erase the existing written text and write another hello world;
What I have tried:
Calendar calendar = Calendar.getInstance();
Date date = new Date();
calendar.setTime(date);
int month = calendar.get(Calendar.DAY_OF_MONTH);
File myFile = new File("log_"+month+".txt");
if(!myFile.exists())
{
myFile.createNewFile();
PrintWriter out = new PrintWriter(myFile);
out.write("Hello World"+System.lineSeparator());
out.close();
System.out.print("First Creation");
return;
}
if(myFile.exists())
{
Path p = Paths.get(myFile.toString());
BasicFileAttributes attr = Files.readAttributes(p, BasicFileAttributes.class);
FileTime creation = attr.creationTime();
DateFormat df = new SimpleDateFormat("MM:dd");
String x = df.format(creation.toMillis());
String y = new SimpleDateFormat("MM:dd").format(calendar.getTime());
attr = null;
if((x).equals(y))
{
FileWriter fw = new FileWriter(myFile.getAbsoluteFile(),true);
BufferedWriter output = new BufferedWriter(fw);
output.write("Hello World" +System.lineSeparator());
output.close();
System.out.print("Existing");
df = null;
}
else {
myFile.delete();
myFile.createNewFile();
PrintWriter out = new PrintWriter(myFile);
out.write("Hello World"+System.lineSeparator());
out.close();
System.out.print(x+y);
}
}
推荐答案
您似乎在混合您的类型和实际逻辑需要。步骤应该是:
You seem to be mixing your types and the actual logic you need. The steps should be:
- 如果文件不存在,则创建它。
- 如果创建月份该文件不是本月,然后删除它,并创建一个新文件。
- 打开输出文件并附加。
- 寻找文件的末尾。
- 将文字写入文件。
- 关闭文件。
这篇关于我的代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文