java read file from network device

前端 未结 3 593
野趣味
野趣味 2020-11-29 10:28

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

相关标签:
3条回答
  • 2020-11-29 10:49

    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.

    0 讨论(0)
  • 2020-11-29 10:53

    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();
        }  
      }
    }
    
    0 讨论(0)
  • 2020-11-29 11:02


    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();
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题