java从网络设备读取文件

发布于 2024-08-09 22:22:47 字数 53 浏览 6 评论 0原文

有人可以帮我找到一个教程或示例java代码来

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

独自唱情﹋歌 2024-08-16 22:22:47

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

在 Windows 上:

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

在 Unix 上:

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

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

一旦您拥有 File 对象,您就可以使用 FileInputStream、FileReader 或任何您想要读取文件的其他内容。

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

示例(来自 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();
    }  
  }
}

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

On Windows:

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

On Unix:

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

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.

Edit for 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

Example (from the Commons HTTP Site):

    // 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();
    }  
  }
}
暮年 2024-08-16 22:22:47

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

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

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

    }

}

客户端代码:

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();
    }

}

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

package com.bebukkit.niton.network.test;

public class ServerStarter {

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

}

客户端:

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();

    }

}

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

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();

    }

}
迟月 2024-08-16 22:22:47

如果您的文件路径位于不同的电脑(网络设备)但连接到同一LAN,那么您可以通过以下两个步骤轻松访问它。

第1步:您需要将网络驱动器(即您想要的文件夹)映射到物理驱动器,例如:
在 Windows 中,\\10.221.222.6/some/path/of/images 路径映射到驱动器,例如 Z:\ 或 Y:\

第 2 步:< /强>

String externalSharedFilePath = "file:Z:/images/";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations(externalSharedFilePath);

}

If your file path in a different pc (i.e. Network devices) but connected to the same LAN, then you can easily access it by using these 2 steps.

Step 1: you need to map the network drive (i.e. your desired folder) into a physical drive, for example:
In Windows, \\10.221.222.6/some/path/of/images path mapped into a Drive like Z:\ or Y:\

Step 2:

String externalSharedFilePath = "file:Z:/images/";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations(externalSharedFilePath);

}
安稳善良 2024-08-16 22:22:47

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

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文