在java中重命名和删除文本文件 [英] Renaming and deleting a text file in java

查看:72
本文介绍了在java中重命名和删除文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图尝试创建两个文本文件,然后写入其中一个文件,用第一个文件重命名第二个文件,然后删除第一个文件。我有一个学校项目,我需要应用这个概念。所以,在我实际在我的项目中应用这个概念之前,我尝试了一个粗略的代码。现在,除了第二个文件不包含第一个文件中的数据外,一切正常。我如何解决这个问题?



这是我的班级,叫做potpie: -



< pre lang =java> package project4;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class potpie {

PrintWriter out ,CR;

文件file1 = 文件( 为trial.txt);
文件file2 = 文件( item .TXT);

public void createfile()抛出 IOException
{
out = new PrintWriter( new FileWriter的(file1的,真));

out.println( User1 + 639755);

cr = new PrintWriter( new FileWriter(file2,true));
cr.close();
out.close();
file1.delete();
file2.renameTo(file1);

}

}



我在trial.txt文件中输出空白,我不知道我犯了错误的地方。请帮帮我。

解决方案

您期待什么?您试图仅将某些内容写入 file1 ,而不是 file2 。但是你删除了 file1 ,因此其内容丢失了。然后你将空 file2 重命名为 file1 ...



以防万一:请不要问我该怎么办?。要问这样的问题,你应该已经解释了你想要实现的目标,而你没有解释。但我现在可以回答:只要用你的头,基本的逻辑;另外,请仔细阅读文档;它非常干净。



-SA


I am trying to experiment with the whole idea of creating two text files then write to one of them, rename the second file with the first file and then deleting the first file. I have a school project where i need to apply this concept. So, before i actually applied the concept in my project, I tried to experiment with a rough code. Now, everything works fine except that the second file doesn't contain the data from the first file. How do i fix this problem?

This is my class which is called potpie:-

package project4;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class potpie {
	
	PrintWriter out,cr;
	
	File file1 = new File("trial.txt");
	File file2 = new File("item.txt");
	
	public void createfile() throws IOException
	{
		out = new PrintWriter(new FileWriter(file1,true));

		out.println("User1" + "639755");

		cr = new PrintWriter(new FileWriter(file2,true));
        cr.close();
        out.close();
		file1.delete();
		file2.renameTo(file1);

}

}


I am getting blank output in my trial.txt file and i don't know where i made the mistake. Please help me out.

解决方案

What would you expect? You tried to write something only to file1, not to file2. But you deleted file1, so its content is lost. Then you renamed empty file2 to file1

Just in case: please, don't ask "what should I do?". To ask such question, you should have explained what you wanted to achieve, which you did not explain. But I can answer to it right now: just use your head, elementary logic; also, read the documentation thoroughly; it is very clean.

—SA


这篇关于在java中重命名和删除文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆