java从网络设备读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1682194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:21:09  来源:igfitidea点击:

java read file from network device

javafilenetworkingio

提问by soField

Can someone help me to find a tutorial or sample java code to

有人可以帮我找到教程或示例 Java 代码吗?

read a file from any machine which is in the same network

从同一网络中的任何机器读取文件

回答by Chris Dail

The simplest way to do this would be to read it using regular file paths.

最简单的方法是使用常规文件路径读取它。

On Windows:

在 Windows 上:

new File("\\server\path\to\file.txt")
// (double-backslashes required for backslashes in path)

On Unix:

在 Unix 上:

First mount the share using Samba (SMB, NFS or whatever other protocol) to some location like /mnt/network. Then you can use:

首先使用 Samba(SMB、NFS 或任何其他协议)将共享挂载到某个位置,例如 /mnt/network。然后你可以使用:

new File("/mnt/network/path/to/file.txt")

Once you have the File object you can use FileInputStream, FileReader or whatever else you want to read the file in.

一旦你有了 File 对象,你就可以使用 FileInputStream、FileReader 或其他任何你想读入文件的东西。

Editfor comments response. If you are using an Applet, you probably want to pull the file from a web server. You can use the built in java.net.URL class but I would recommend this if you have to do more than just simple stuff: http://hc.apache.org/httpclient-3.x/index.html

编辑评论回复。如果您使用的是 Applet,您可能希望从 Web 服务器拉取文件。您可以使用内置的 java.net.URL 类,但如果您要做的不仅仅是简单的事情,我会推荐这个:http: //hc.apache.org/httpclient-3.x/index.html

Example (from the Commons HTTP Site):

示例(来自 Commons HTTP 站点):

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

回答by Matthew Sowders

Try the following URL for a tutorial http://www.roseindia.net/java/beginners/construct_file_name_path.shtml

尝试使用以下 URL 获取教程http://www.roseindia.net/java/beginners/construct_file_name_path.shtml

I think the best way is to use java.net.URLto open a InputSteam, because you can generalize it to files, that are not necessarily on the same network.

我认为最好的方法是使用java.net.URL打开 InputSteam,因为您可以将其概括为文件,这些文件不一定在同一网络上。

回答by Niton


This is not that simple! To use Server Client Aplications you need a Network API.
I have 1 by DeBukkit and an extended version. If you would to send Files I will suggest my one (Server Client Extended .jar) becazse there is an Option to send Files (FilePacket.java).
This are the links to the libs: All Libs


这不是那么简单!要使用服务器客户端应用程序,您需要一个网络 API。
我有 1 个 DeBukkit 和一个扩展版本。如果你想发送文件,我会推荐我的(服务器客户端扩展 .jar),因为有一个发送文件的选项(FilePacket.java)。
这是库的链接:所有


Code for Server for Client Server Extended:


客户端服务器扩展的服务器代码:

public class TestServer extends Server {

    public TestServer() {
        super(29898, true, true,true);
        registerMethod("bt", new FileReciver() {

            @Override
            public void onCompleteRecive(FileInfo data) {
                System.out.println("Completely recived : "+data);
                Path p = Paths.get(data.getName());
                try {
                    Files.createFile(p);
                    Files.write(p, data.getContent());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
             /**
             * @see com.bebukkit.niton.network.packets.buffer.BufferedPacketReciver#run(com.bebukkit.niton.network.packets.Packet, java.net.Socket)
             */
            @Override
            public void run(Packet<? extends Serializable> msg, Socket socket) {
                super.run(msg, socket);
                sendMessage(new Packet<Boolean>("", null), socket);
            }
        });
    }

    @Override
    public void preStart() 
    {
        registerMethod("msg", new ReciveMethod() {

            @Override
            public void run(Packet<? extends Serializable> msg, Socket socket) {
                broadcastMessage(msg);
            }
        });
    }

    @Override
    public void onWrongDataPacketException(ClassNotFoundException e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onReceivePacketError(IOException e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPacketReckognized(ServerSocket socket) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPacketSendException(Exception e, Packet<? extends Serializable> message, Socket socket2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSendPacketToNotConnectedClient(Packet<? extends Serializable> message, Socket socket2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onBrodcast(Packet<? extends Serializable> pack) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onServerStartError(IOException e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onServerStop() {
        // TODO Auto-generated method stub

    }

}

Code for Client:

客户端代码:

package com.bebukkit.niton.network.test;

import java.io.IOException;
import java.io.Serializable;
import java.net.Socket;
import java.util.Scanner;

import com.bebukkit.niton.network.Client;
import com.bebukkit.niton.network.packets.Packet;
import com.bebukkit.niton.network.packets.ReciveMethod;

public class TestClient extends Client {

    public TestClient() {
        super("localhost", 29898, 5000, false,true);
        registerMethod("msg", new ReciveMethod() {

            @Override
            public void run(Packet<? extends Serializable> msg, Socket socket) {
                System.out.println(msg.getData());
            }
        });
        registerMethod("replay", new ReciveMethod() {

            @Override
            public void run(Packet<? extends Serializable> msg, Socket socket) {
                System.out.println("REREplay");
            }
        });
    }

    @Override
    public void onSocketClosingFail() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLoginPacketSendingFailed(IOException ex) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectionError(IOException ex) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMessageReciveError(Exception ex) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPacketSendError(Exception ex, Packet<? extends Serializable> pack) {
        // TODO Auto-generated method stub

    }
    @Override
    public void start() {
        super.start();
    }

}


You need a seperated Server + Client Starter:


您需要一个单独的服务器 + 客户端启动器:

package com.bebukkit.niton.network.test;

public class ServerStarter {

    public static void main(String[] args) {
        new TestServer();
    }

}

Client:

客户:

package com.bebukkit.niton.network.test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import javax.swing.JFileChooser;

import com.bebukkit.niton.network.packets.Packet;
import com.bebukkit.niton.network.packets.buffer.BufferedPacket;
import com.bebukkit.niton.network.packets.file.FileInfo;
import com.bebukkit.niton.network.packets.file.FilePacket;

public class ClientStarter {

    public static void main(String[] args) throws IOException {
        TestClient tc = new TestClient();
        tc.start();

        new Thread(new Runnable() {

            @Override   
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                JFileChooser c = new JFileChooser("Choose a file to upload");
                c.setFileSelectionMode(JFileChooser.FILES_ONLY);
                c.showDialog(null,"Upload");
                File f = c.getSelectedFile();
                try {
                    tc.sendMessage(new FilePacket("file", f));
                    tc.sendMessage(new Packet<String>("replay","test"));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

    }

}