membersound
membersound

Reputation: 86915

How to inject a network file resource with Spring?

How can I tell Spring that the resource is supposed to be a network resource, and let it autowire accordingly?

@Value("\\MY-MACHINE\thefile.txt")
private Resource file;

Result:

Caused by: java.io.FileNotFoundException: class path resource [MY-MACHINE\thefile.txt] cannot be resolved to URL because it does not exist

Upvotes: 3

Views: 2507

Answers (4)

membersound
membersound

Reputation: 86915

As nobody seems to be aware of, I found out that it's just necessairy to use double slashes like:

@Value("\\\\MY-MACHINE\\thefile.txt")
private Resource file;

In some cases you may required a file: statement before, like: file:\\\\MY-MACHINE\\thefile.txt"

Upvotes: 1

Maciej Walkowiak
Maciej Walkowiak

Reputation: 12932

I am assuming your application is deployed on Windows. I don't have anywhere windows workstation to test it, but as far as I remember this is how it goes:

  • create symbolic link to your network location:

    mklink /D C:\my-machine \\MY-MACHINE\
    
  • refer to this symlink with absolute path:

@Value("file:///C:/my-machine/thefile.txt")
private Resource file;

Upvotes: 1

Wim Deblauwe
Wim Deblauwe

Reputation: 26878

Accessing a file on a Windows share will not work directly. See connecting to shared folder in windows with java for more info on how to do that.

Upvotes: 0

Xstian
Xstian

Reputation: 8282

This is the easiest way using classpath

import org.springframework.core.io.Resource;

@Value("classpath:<path to file>")
private Resource file;

Upvotes: 0

Related Questions