Search code examples
javafilejava.util.scannerfileinputstreamfileoutputstream

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


Hi so I have a client and a host. I want the client to open a file whose file name is obtained from user input and then read the numbers stored on the file and send the numbers to the host.

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

At the moment thats what I have. I am stuck on how to scan the numbers on the file. Obviously it sends the file name to host as I set

String msgToSend = input; 

The file looks like this (Anthony.txt).

1    
2    
3    
4    
5

Numbers are stored like that in the file. Any ideas on how could I instantiate a Player object and set the name and scores for the player from the file data and transfer the Player object to the server?

My host code:

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

First I was asked to make a game which creates a player and stores the scores into a file.

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

}

The application:

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

Solution

  • This is one way you could do it,

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

    If you want to send the Numbers all at once you could just store them in an Array or StringBuilder first then do with it what you want.


    EDIT

    I see you want to send the Player object, not sure how to do that, atleast now you can see how to read the text file.