使用java io从远程机器读取文件

时间:2018-05-22 07:46:51

标签: java

public static void main(String[] args) throws IOException, URISyntaxException {

    String ipaddress = "10.20.220.187";
    String folderpath = "C:\\Users\\Administrator\\Desktop\\KS_testData\\";
    String fileName = "test.txt";

    String inputFileName = "file:\\\\"+ipaddress+"\\"+folderpath+fileName;

    System.out.println(" inputFileName "+inputFileName);

    File file = new File(inputFileName);
    FileReader inputFileReader = new FileReader(file);
    BufferedReader inputStream = new BufferedReader(inputFileReader);

    String inLine = null;
    while ((inLine = inputStream.readLine()) != null) {
        System.out.println(inLine);
    }
}

这里我试图连接到提供的ipaddress并在其上读取文件, 指定的文件夹名称是共享文件夹,我得到FileNotFoundException。 任何人都可以建议我做错了什么。

收到的输出是:

    inputFileName file:\\10.20.220.187\C:\Users\Administrator\Desktop\KS_testData\test.txt
Exception in thread "main" java.io.FileNotFoundException: file:\10.20.220.187\C:\Users\Administrator\Desktop\KS_testData\test.txt (The filename, directory name, or volume label syntax is incorrect)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileReader.<init>(FileReader.java:72)
    at com.sv.ppsdemos.remote.RemoteReadAndWrite.main(RemoteReadAndWrite.java:22)

2 个答案:

答案 0 :(得分:0)

String inputFileName = "file:\\\\"+ipaddress+"\\"+folderpath+fileName;

问题出在这里。这不是文件名,而是URL。

摆脱file:部分。

答案 1 :(得分:-1)

尝试使用此jcifs

SmbFile fileToRead= new SmbFile(smb://192.168.0.27/export/myFile.txt);

希望这会有所帮助,