从用户输入打开文件,然后读取存储在文件中的值

Open file from user input and then read the values stored on the file

你好,我有一个客户和一个主机。我希望客户端打开一个文件,其文件名是从用户输入中获取的,然后读取存储在文件中的数字并将数字发送到主机。

Socket clntSock = new Socket("127.0.0.1", 6000);
Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
File file = new File(input);
String msgToSend = input;
byte[] bytesToSend = msgToSend.getBytes();
OutputStream out = clntSock.getOutputStream();
out.write(bytesToSend);
out.close();
clntSock.close();

目前这就是我所拥有的。我被困在如何扫描文件上的数字上。显然它会按照我设置的方式将文件名发送到主机

String msgToSend = input; 

文件看起来像这样 (Anthony.txt)。

1    
2    
3    
4    
5

数字存储在文件中。关于如何实例化 Player 对象并根据文件数据为玩家设置名称和分数并将 Player 对象传输到服务器的任何想法?

我的主机代码:

 ServerSocket servSock = new ServerSocket(6000);
 PrintStream fileOut = new PrintStream("Datafromclient.txt");

 while (true)
 {
    Socket clntSock = servSock.accept();
    InputStream in = clntSock.getInputStream();
    byte[] receiveBuf = new byte[BUFSIZE];
    int recvMsgSize = in.read(receiveBuf);
    System.out.println("received data >> "+ new String(receiveBuf));
    fileOut.println(""+ new String(receiveBuf));
    in.close();
    clntSock.close();

首先我被要求制作一个游戏,它创建一个玩家并将分数存储到一个文件中。

玩家class:

//Class declaration of Player class
public class Player
{
/*--------------- Data Fields ---------------------------------------
Attributes of the class
*/
private String name;
private int playerId;
private int bestScore;
private static int numberOfPlayers = 0;
private ArrayList<Integer> scores = new ArrayList<Integer>();

/* -------------- CONSTRUCTOR --------------------------------------
*/
public Player(String name)
{
    this.name = name;
    numberOfPlayers++;
    playerId = numberOfPlayers;

}

//Create set method for setName
public void setName(String name)
{
    this.name = name;
}

//Create set method for setScores
public void setScore(int score)
{
    scores.add(score);
}

//Create get method for getPlayerId
public int getPlayerId()
{
    return this.playerId;
}

//Create get method for getName
public String getName()
{
    return this.name;
}

//Create get method for getScores
public ArrayList<Integer> getScores()
{
    return scores;
}

//Create get method for getBestScore
public int getBestScore()
{
    return bestScore;
}

//Method to expose the value of numberOfPlayers
public static int getNumberOfPlayers()
{
    return numberOfPlayers;
}

//Create get method for calcualteAverage
public double calculateAverage()
{
    Integer sum = 0;
    if(!scores.isEmpty())
    {
        for(Integer score : scores)
        {
            sum += score;
        }
        return sum.doubleValue() / scores.size();
    }
    return sum;

}

应用程序:

    String name;
    int scores;


    PrintStream fout = new PrintStream(new File("PlayerData2.txt"));
    //Create Scanner object
    Scanner input = new Scanner (System.in);
    while(true)
    {
    //Ask user for name
    System.out.printf("\n Enter Player Name:");
    name = input.nextLine();
    //Create a Player Object
    Player player1 = new Player(name);


    for (int i=0; i<5; i++)
        {
            //Ask user for number input
            System.out.println("Please pic a number between 1 - 20");
            player1.setScore(Integer.parseInt(input.nextLine()));

            Random rand = new Random();
            int answer = rand.nextInt(20) + 1;
            System.out.println(answer);
            System.out.println(""+player1.getScores());
            if ((answer >= player1.getScores().get(i)))
            {
                    System.out.println("Your guess is too low");
            }
            else if(answer <= player1.getScores().get(i))
            {
                    System.out.println("Your guess is too high");
            }


        }

    fout.println( "" + player1.getName() );
    fout.println( "" + player1.getScores().get(0) );
    fout.println( "" + player1.getScores().get(1) );
    fout.println( "" + player1.getScores().get(2) );
    fout.println( "" + player1.getScores().get(3) );
    fout.println( "" + player1.getScores().get(4) );

这是您可以做到的一种方法,

// Use a Scanner to read the File
Scanner readFile = new Scanner(file);

// Loop Through Each Line
while(readFile.hasNext()) {

    // Get Number as a Byte
    byte[] number = readFile.nextLine().getBytes();

    // Write number to OuputStream
    out.write(number);

    // Flush OuputStream, Never forget to Flush your OutputStreams
    out.flush();

}

如果您想一次发送所有数字,您可以先将它们存储在数组或 StringBuilder 中,然后根据需要进行处理。


编辑

我看到你想发送 Player 对象,不知道该怎么做,至少现在你可以看到如何读取文本文件。