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

时间:2015-04-13 21:45:16

标签: java file java.util.scanner fileinputstream fileoutputstream

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

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

1 个答案:

答案 0 :(得分:0)

这是你可以做到的一种方式,

// 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对象,不知道怎么做,至少现在你可以看到如何阅读文本文件了。