Java - .txt文件被覆盖或删除

问题描述 投票:0回答:1

我有一个程序,服务器获取客户端的IP地址,如果他们没有正确登录到服务器,则将其打印到.txt文件。然后,如果客户端回来尝试再次登录,服务器应该读取该文件并查看它是否与用户的IP地址匹配。如果是,服务器将通过关闭与客户端的连接来禁止用户。

问题是每次重新启动服务器代码时,都会删除txt文件中用户的ip地址。这不应该发生 - 用户的ip需要永久保存在txt文件中。

我以为它可能与括号,循环的位置有关,或者尝试重置为0?

我有什么想法可以解决这个问题吗?

我将发布我认为的相关代码如下:

    import java.lang.*;
import java.io.*;
import java.net.*;

class Server {
    public static void main(String args[]) throws IOException {
        String welcome = "Welcome! The server is now connected.";
        String login = "Enter username and password: ";
        String message; 
        //PrintWriter writer = new PrintWriter("userIP.txt");
        FileWriter writer = new FileWriter("userIP.txt", true);


        try {
            //Detecting the localhost's ip address
            InetAddress localaddr = InetAddress.getLocalHost();
            System.out.println("SERVER\n");
            System.out.println ("Local hostnameIP: " + localaddr );

            // Creating a server socket for connection
            ServerSocket srvr = new ServerSocket(1234);
            System.out.println("Waiting for connection on "+localaddr);
            // Accept incoming connection
            Socket skt = srvr.accept();
            System.out.print("Server has connected!\n");
            // get Input and Output streams
            PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
            out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream())); 
            System.out.print("Sending string: '" + welcome + "'\n");
            out.println(welcome);
            //String ip = localaddr.getHostAddress();
            InetAddress clientInetAddress = skt.getInetAddress();
            String ip = clientInetAddress.getHostAddress();

            //read file


String checkIP = "userIP.txt";

        try {

                BufferedReader infile = new BufferedReader (new FileReader("userIP.txt"));
                String line;
                int numofline = 1;
                System.out.println("Beginning to read the file");
                line = infile.readLine();

                while (line!= null) {
                    System.out.println("*******Line " + numofline++ + "*******");
                    String data[] = line.split(",");

                    for (int i=0; i<data.length; i++) {
                        System.out.println("Element #" + i + " "+data[i]);
                    }
                    line = infile.readLine(); //reading the next line

                        if (data.equals(ip)) {
                            System.out.println("IP MATCHES");

                            //closing server
                            out.println("You are banned. Server closing.");
                            out.close();
                            skt.close();
                            srvr.close();
                        }
                        infile.close();
                    }


                            }           catch (FileNotFoundException ex) {
                System.out.println("Unable to open file '" + checkIP + "'");            }           catch(IOException ex) {
                System.out.println("Error reading file '" + checkIP + "'");             }
                        //login attempts            int tries = 4;          while (tries>0) {
                out.println(login);

                //login
                String username = in.readLine();
                System.out.println("Client's username: " + username);

                String password = in.readLine();
                System.out.println("Client's password: " + password);

                if (username.equals("hello123") && password.equals("mypass")) {
                    out.println("Correct login!");
                    System.out.println ("Client's IP Address: " + ip);
                    tries=-1;
                }

                else  { //if wrong login - give 3 more tries

                    tries--;
                    System.out.println("Number of tries left: " + tries);
                    out.println("Try again. Login attempts left - " + tries);

                }           }


                if (tries<=0){
                out.println("Wrong login - server closing");
                out.close();
                skt.close();
                srvr.close();

                //ban ip address permanently 
                System.out.println("local: " + localaddr.getHostAddress()); 
                System.out.println("client: " + ip);

                //writer.println(localaddr.getHostAddress()); //write ip address to file
                writer.println(ip);
                writer.close();
                            }
do {

            message=in.readLine();
            System.out.println("client> "+message);
            if (message.equals("password")){
                out.println("Access Granted");
            }else if (message.equals("bye")){
                out.println("Server closing");
                System.out.println("server> Server closing");
            }
        }while(!message.equals("bye"));
        out.close();
        skt.close();
        srvr.close();
    }catch(BindException e){
        //e.printStackTrace();
        System.out.print("A server is already running on the same port.");        
    }catch(SocketException e) {
        //e.printStackTrace();
        System.out.print("Client has disconnected rudely.");
    }catch(Exception e){
        //e.printStackTrace();
        System.out.print(":( Whoops! It didn't work!\n");

    }
}
java filereader overwrite filewriter
1个回答
0
投票

writer.close()之后尝试这个特别是如果您使用Linux基本服务器:

FileOutputStream fos=new FileOutputStream(fileToEdit);
fos.getFD().sync();

具体来说,您需要触发称为fsync()的Linux系统调用,该调用告诉文件系统确保将所有缓冲区写入磁盘。

© www.soinside.com 2019 - 2024. All rights reserved.