我有一个程序,可以根据命令行输入替换文件中的文本。目前,它创建一个临时文件,并将带有替换文本的字符串写入新的临时文件中。该程序在我校园计算机实验室的桌面上运行,但是当我尝试在我的个人笔记本电脑上运行它时,会创建临时文件,我可以通过打印其规范路径找到它,并且 file.exists() 返回 true ,但它没有显示在我的桌面上。 使用 Windows 资源管理器进行搜索不会产生任何结果。
我运行的是 Windows 7 并使用 TextPad。有谁知道可能是什么原因造成的?我可以提供任何其他必要的信息。
编辑:我在 Mac Pro 2011 上运行 Windows 7,如果这有什么区别的话。
编辑:我发现了问题。我下载了 Comodo 防病毒软件,每当我创建文件时,它都会在 VTRoot 文件夹中创建它以用于沙箱目的。我能够更改设置并解决我的问题。
import java.io.*;
import java.util.*;
public class ReplaceText{
public static void main(String[] args)throws IOException{
if(args.length != 2){
System.out.println("Incorrect format. Use java ClassName textToReplace filename");
System.exit(1);
}
File source = new File(args[1]);
if(!source.exists()){
System.out.println("Source file " + args[1] + " does not exist.");
System.exit(2);
}
File temp = new File("temp.txt");
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(input.hasNext()){
String s1 = input.nextLine();
String s2 = s1.replace(args[0], "a");
output.println(s2);
}
}
}
}
最佳答案
如果您看不到 temp.txt 文件,那是因为它位于您的 java 源代码所在的项目目录中。但是,如果您找到它,那么它也将不包含任何内容。原因是您没有关闭刚刚放置的文件的输出流
output.close()
在 while 循环之后。
关于Java程序创建文件,但文件不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42882185/