Home > OS >  How can I get specific information out of a .txt file in java?
How can I get specific information out of a .txt file in java?

Time:10-26

I'm new to Java and I can't find a way to open a text file and tell my computer ok line 1 from 0 to the " " it's the first node, from " " to " " it's the second node and from " " to \n it's the weight.

This is an extract of the said .txt file

Eskildstrup Maribo 28

Eskildstrup NykøbingF 13

Eskildstrup Vordingborg 25

Haslev Korsør 60

Haslev Køge 24

The point of the program should be to create a graph and then use prim... It shouldn't be too difficult but I'm having a real tough time doing the sorting in the first place...

I have examples of how I did it on C :

while(std::getline(game, s))
        {
            std::string n=s.substr(0,s.find("="));
            if(n==m_nom)
            {
                existe=true;
                std::string m=s.substr(s.find("=") 1,100000000);
                std::string o=m.substr(0, m.find(";"));
                std::string coin=m.substr(m.find(";") 1, 100000000);
                std::cout<< o<<std::endl<<coin<<std::endl;
    
                std::string delimiter = ",";

or

    for (int i = 0; i < m_ordre; i  )
        {
            int tempId=0;
            std::string tempNom;
            double tempAltitude=0;
    
            ifs >> tempId >> tempNom >> tempAltitude;
            m_stations.push_back(new Sommet(tempId, tempNom, tempAltitude));
        }

But I can't seem to be able to do the same in Java. For now, I have my node, vertices, and graph classes.

This is what my graph class looks like rn...

class Graph
{
    public Graph(File doc){
        try {
            BufferedReader br= new BufferedReader(new FileReader(doc));
            String s, line, unique, del=" ";
            while ((s= br.readLine())!= null)
                System.out.println(s);
            while () {

            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

CodePudding user response:

A very basic approach, but might be sufficient:

  1. read the lines of the file
  2. split each line by whitespace(s)
  3. handle the results (for instance, create an edge for your graph)

The following example uses java.nio.Path and java.nio.Files for the operations 1. and 2. mentioned above:

public static void main(String[] args) throws IOException {
    String fileLocation = "/path/to/your/graph-coords.txt";
    // create a Path from the String
    Path filePath = Paths.get(fileLocation);
    // if everything is fine with the file (checks omitted for brevity), read its lines
    List<String> lines = Files.readAllLines(filePath);
    // then handle each line:
    lines.forEach(line -> {
        // split each line by an arbitrary number of whitespaces
        String[] lineValues = line.split("\\s ");
        // and do what you want with the results, e.g. create an edge of the graph
        System.out.println(lineValues[0]   " --"   lineValues[2]   "km--> "   lineValues[1]);
    });
}

The output of this code is

Eskildstrup --28km--> Maribo
Eskildstrup --13km--> NykøbingF
Eskildstrup --25km--> Vordingborg
Haslev --60km--> Korsør
Haslev --24km--> Køge

As an example of handling the values, I just rearranged them into a different String assuming the weight is a distance in kilometers. Having all the lines of the file in a Collection makes checking for linebreaks obsolete (a really handy thing of this library).

Create the initial String with respect to the system of your computer, I used a Linux/MacOs style path, on Windows, you will have to provide a drive letter, I think.

This answer only shows how to read the lines and split them into single values. It does not check for existence of or read access to the file, though possible with java.nio (e.g. java.nio.Files.isRegularFile(Path filePath) or java.nio.Files.isReadable(Path filePath) and java.nio.Files.exists(Path filePath)). Exception handling is mandatory, here I just made the main method throw an IOException to get the code compiled.

  • Related