简体   繁体   中英

Java Not able to create a file in windows shared folder from Linux

I am trying to create a file in a shared folder using the below code. I am able to do it when i run this code on windows. But however when i run the same code on linux it is not working.

In liunx it is creating a file named "\\192.168.1.102\\share\\1.pdf" in the folder where i run this java code instead of creating a file 1.pdf in the shared folder "\\192.168.1.102\\share\\".

It seems like while running on Linux the server was not identifying the path as a shared location, Instead it reads that as it's local path.

Are there any other ways to create a file in the shared folder? Could anyone please help me in resolving this?

public class Test {

    public static void main(String args[]) {

        String s1 ="\\\\192.168.1.102\\share";
        try{

            FileOutputStream fos = new FileOutputStream(s1+"\\1.pdf");
            fos.write(("Testing Success").getBytes());
            fos.close();
        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println(e.toString());
        }

        File file = new File(s1);
        System.out.println(file.exists());
    }
}

Linux simply doesn't support \\\\ip\\folder path syntax.

You have to mount you shared folder before use.

Check if you have enough permissions to write file on the shared folder. Or try running Jar of your code as administrator.

(1) Please use java function File.separator instead of "\\" in file path to make it platform independent.

As Windows support "\\\\" and linux supports "/".

(2) Check you have permission to write on that directory by using chmod command.

Assuming the file-system is properly mounted in the path you're using, the code won't work cross-platform because paths in Windows use \\ as a segment separator, while paths in Linux use / .

You should use cross-platform code to generate paths. The File class has a static String member called separator that will have the correct value for the platform.

String myPath = File.separator + "home" + File.separator + "bob"

The above will produce \\home\\bob in Windows, /home/bob in Linux/OSX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM