mercredi 4 novembre 2015

How can I use Java to read a file

So I have this piece of code in which I want to allow the user to enter in a String of any length and it encrypts the code. To make this more than a basic project, I thought it would be cool to have a 'save' feature where the user can pickup from later on.
The problem arises here. I was going through Youtube and through a youtuber I learnt how to create a file and write to the file. When I went to the part where I read the file (load) I saw that I need to create a variable for every single character in the file. As I will not know how many variables to make, I am stuck.
In his code (I will display it) he uses a while loop to loop through the contents of the file and using a variables he prints out its contents. My code is as follows:

import java.util.*;  
public class Sep {
    private Formatter x;
    public void openfile () {
        try {
            x = new Formatter("Gogo.txt");
        }
        catch (Exception e) {
            System.out.println("You have an error mate!!");
        }
    }
    public void addStuff() {
        x.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
        }
    public void closeFile () {
        x.close();
    }
}

As the user will be entering whatever he wants, I have no bloody clue on how many variables to make. The youtuber has this:

import java.util.*;


public class Sep {
    private Formatter g;
    private Scanner x;
    public void openfile () {
        try {
            g = new Formatter("Gogo.txt");
            x = new Scanner(new File("gogo.txt"));
        }
        catch (Exception e) {
            System.out.println("You have an error mate!!");
        }
    }
    public void addStuff() {
        g.format("%s%s%s%s", "Gogo will return!!", "Stronger than ever!!", "Faster than can be seen!!", "And he is out for blood...");
        }
    public void readFile() {
        while(x.hasNext()) {
            String a = x.next();
            String b = x.next();
            String c = x.next();
            System.out.printf("%s %s %s\n", a,b,c);
        }
    public void closeFile () {
        x.close();
    }
}

Aucun commentaire:

Enregistrer un commentaire