java - 为什么我不能在本地主机上使用 FileWriter 写入文件,但它可以在其他机器上运行?
问题描述
我想在文件中写行,在我的本地机器上,文件在下面/home/localuser/Desktop/myProgram/files
,当我把它们放在服务器机器上时,它们在/userhome/my_name
.
当我在本地机器上运行程序时,它会在下面创建输出文件,/home/localuser/Desktop/myProgram/files/output.txt
并检测该文件是否已经存在但它没有写入其中,也不会引发任何异常。在服务器上,它创建并检测下面的文件/userhome/my_name/output.txt
并将其写入其中。
如果文件已存在,则代码如下创建并使其为空:
private static void createFile(String fileName){
try{
File printerFile = new File(fileName);
if(printerFile.createNewFile()){
System.out.println("File created: " + printerFile.getName());
}else{
System.out.println("File already exists. Emptying " + fileName);
emptyFile(fileName);
}
} catch (IOException e){
System.out.println("Problem while creating new file");
e.printStackTrace();
}
}
private static void emptyFile(String filename){
try{
new PrintWriter(filename).close(); // make the file empty
}catch (IOException e){
System.out.println("Problem while emptying the file");
e.printStackTrace();
}
}
然后写内容:
process Printer_P{
String messageToPrint; // used to store the message that the printer get from the client
PrinterCommand command; // used to store the action that the client asked for
try{ // try and catch the openning of a file writer
out = new FileWriter(filename,true);
}catch(IOException e){
System.out.println("Problem while openning a new FileWriter in Printer.jr");
e.printStackTrace();
}
System.out.println(printerName +" " + "POWER ON");
while(true){
receive action(command, messageToPrint); // wait until it receive an action
if(command == PrinterCommand.PRINT){
System.out.println(printerName + " " + messageToPrint);
try{ // try and catch the writting action
out.write(messageToPrint+"\n");
}catch(IOException e){
System.out.println("Problem while writting in the output file in Printer.jr");
e.printStackTrace();
}
}else if (command == PrinterCommand.CLOSE){
try{
out.close();
}catch (Exception e){
System.out.println("Problem while close the filewriter in Printer.jr");
e.printStackTrace();
}
break;
}
}
System.out.println(printerName +" " + "SHUTDOWN");
}
}
为什么当我在本地机器上使用它时它不写入文件,但在服务器机器上它却这样做?
解决方案
推荐阅读
- python - 每周队列,python pandas,sql
- sql-server - SQL Server 2017 vs SQL Server 2012 性能问题
- java - javascript 错误:无法在“文档”上执行“elementsFromPoint”:提供的双精度值是非有限的
- instagram - 从 instaloader 下载 1 周数据
- python - 如何计算多个数据帧之间的重叠行?
- javascript - 如何阻止空输入字段影响javascript计算
- angular - 文件上传已被 CORS 策略阻止
- regex - 正则表达式提取 URL 的字母数字部分?
- python - 硒中发现元素的顺序
- django - 检查 Django 中多列的唯一性