如果我运行此代码,则不会发生任何情况,甚至不会捕获异常。该字符串不会出现在 test.txt 文件中。 test.txt 文件的路径为~/home/joci/Joci。我错了什么?
public static void main(String[] args) {
try{
String text = "this is just a test ";
FileWriter fw = new FileWriter("/home/joci/Joci test.txt");
fw.write(text);
fw.close();
}catch(IOException e ){
System.out.println("Something went wrong ");
}
最佳答案
首先,我你的问题是
"/home/joci/Joci test.txt"
不表示 Linux 下的有效文件名;所以你只需删除那个空格即可;或者将其替换为 _ 或 - 例如。或者使用 \\
来转义该空格。
但我刚刚尝试过:
import java.io.*;
public class Test {
public static void main(String[] args) {
try{
String text = "this is just a test ";
FileWriter fw = new FileWriter("/home/myhome/tmp/out 21.txt");
fw.write(text);
fw.close();
}catch(IOException e ){
System.out.println("Something went wrong ");
}
}
}
这工作很好。因此,您的设置中一定还有其他原因导致了此问题!
此外:~
字符是 Linux shell 的一项功能。 JVM不知道这个字符的意思是“家”;因此你应该根本不在你的java源代码中使用它!
关于java - Linux上的文件写入路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41263743/