首页 > 解决方案 > 为什么我不能在本地主机上使用 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");
    }
}

为什么当我在本地机器上使用它时它不写入文件,但在服务器机器上它却这样做?

标签: javafilefilewriter

解决方案


推荐阅读