How to read integers from a file using BufferedReader from Java?How do I efficiently iterate over each entry in a Java Map?How do I check whether a file exists without exceptions?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I create a Java string from the contents of a file?How do I generate random integers within a specific range in Java?How do I include a JavaScript file in another JavaScript file?How to read all files in a folder from Java?How to read a file line-by-line into a list?How do I convert a String to an int in Java?

Can you shove a friendly creature?

Partial Fractions: Why does this shortcut method work?

How does shared_ptr<void> know which destructor to use?

Can I say "Gesundheit" if someone is coughing?

Approximating an expression for a potential

Reasons for using monsters as bioweapons

Can there be multiple energy eigenstates corresponding to the same eigenvalue of a Hamiltonian (Pauli-X)?

What exactly is Rhumb-line control in the context of a launch trajectory?

Phase portrait of a system of differential equations

How does なんていう + のも function in this sentence?

Polygons crash kernel?

How to call made-up data?

Why is the Vasa Museum in Stockholm so Popular?

Representation of the concatenation at the type level

Who's behind community AMIs on Amazon EC2?

Different answers of calculations in LuaLaTeX on local computer, lua compiler and on overleaf

Declaring a visitor to the UK as my "girlfriend" - effect on getting a Visitor visa?

On the expression "sun-down"

Have you been refused entry into the Federal Republic of Germany?

Went to a big 4 but got fired for underperformance in a year recently - Now every one thinks I'm pro - How to balance expectations?

Is it moral to remove/hide certain parts of a photo, as a photographer?

Is law enforcement responsible for damages made by a search warrant?

How to handle many times series?

How can I perform a deterministic physics simulation?



How to read integers from a file using BufferedReader from Java?


How do I efficiently iterate over each entry in a Java Map?How do I check whether a file exists without exceptions?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I create a Java string from the contents of a file?How do I generate random integers within a specific range in Java?How do I include a JavaScript file in another JavaScript file?How to read all files in a folder from Java?How to read a file line-by-line into a list?How do I convert a String to an int in Java?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am working with BufferedReader in Java and was hoping for some guidance when it comes to reading integers.



To summarize, each line of the input file will represent one edge in an undirected graph. It will contain two integers, the endpoints of the edge, followed by a real number, the weight of the edge. The last line will contain a -1, to denote the end of input.



I have created a BufferedReader object and initialized an integer variable and



The format of the file is as follows:



 0 1 5.0
1 2 5.0
2 3 5.0
...
5 10 6.0
5 11 4.0
17 11 4.0
-1


public static void processFile(String inputFilePath) throws IOException 


This is what I have attempted thus far, but I wondering how I can take each line of code, and have the first number be the "start" variable, the second number be the "end" variable, and the third number be the "weight" variable? I saw some solutions online to create an array but because of the format of my file I am somewhat confused. I can help clarify any details about










share|improve this question



















  • 1





    Use while ((line = fileReader.readLine()) != null) {, then parse the line to extract the 3 numbers.

    – Andreas
    Mar 27 at 1:45

















0















I am working with BufferedReader in Java and was hoping for some guidance when it comes to reading integers.



To summarize, each line of the input file will represent one edge in an undirected graph. It will contain two integers, the endpoints of the edge, followed by a real number, the weight of the edge. The last line will contain a -1, to denote the end of input.



I have created a BufferedReader object and initialized an integer variable and



The format of the file is as follows:



 0 1 5.0
1 2 5.0
2 3 5.0
...
5 10 6.0
5 11 4.0
17 11 4.0
-1


public static void processFile(String inputFilePath) throws IOException 


This is what I have attempted thus far, but I wondering how I can take each line of code, and have the first number be the "start" variable, the second number be the "end" variable, and the third number be the "weight" variable? I saw some solutions online to create an array but because of the format of my file I am somewhat confused. I can help clarify any details about










share|improve this question



















  • 1





    Use while ((line = fileReader.readLine()) != null) {, then parse the line to extract the 3 numbers.

    – Andreas
    Mar 27 at 1:45













0












0








0








I am working with BufferedReader in Java and was hoping for some guidance when it comes to reading integers.



To summarize, each line of the input file will represent one edge in an undirected graph. It will contain two integers, the endpoints of the edge, followed by a real number, the weight of the edge. The last line will contain a -1, to denote the end of input.



I have created a BufferedReader object and initialized an integer variable and



The format of the file is as follows:



 0 1 5.0
1 2 5.0
2 3 5.0
...
5 10 6.0
5 11 4.0
17 11 4.0
-1


public static void processFile(String inputFilePath) throws IOException 


This is what I have attempted thus far, but I wondering how I can take each line of code, and have the first number be the "start" variable, the second number be the "end" variable, and the third number be the "weight" variable? I saw some solutions online to create an array but because of the format of my file I am somewhat confused. I can help clarify any details about










share|improve this question














I am working with BufferedReader in Java and was hoping for some guidance when it comes to reading integers.



To summarize, each line of the input file will represent one edge in an undirected graph. It will contain two integers, the endpoints of the edge, followed by a real number, the weight of the edge. The last line will contain a -1, to denote the end of input.



I have created a BufferedReader object and initialized an integer variable and



The format of the file is as follows:



 0 1 5.0
1 2 5.0
2 3 5.0
...
5 10 6.0
5 11 4.0
17 11 4.0
-1


public static void processFile(String inputFilePath) throws IOException 


This is what I have attempted thus far, but I wondering how I can take each line of code, and have the first number be the "start" variable, the second number be the "end" variable, and the third number be the "weight" variable? I saw some solutions online to create an array but because of the format of my file I am somewhat confused. I can help clarify any details about







java file io integer bufferedreader






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 27 at 1:42









user10335564user10335564

475 bronze badges




475 bronze badges










  • 1





    Use while ((line = fileReader.readLine()) != null) {, then parse the line to extract the 3 numbers.

    – Andreas
    Mar 27 at 1:45












  • 1





    Use while ((line = fileReader.readLine()) != null) {, then parse the line to extract the 3 numbers.

    – Andreas
    Mar 27 at 1:45







1




1





Use while ((line = fileReader.readLine()) != null) {, then parse the line to extract the 3 numbers.

– Andreas
Mar 27 at 1:45





Use while ((line = fileReader.readLine()) != null) {, then parse the line to extract the 3 numbers.

– Andreas
Mar 27 at 1:45












3 Answers
3






active

oldest

votes


















1














Switch up to readLine and use a Scanner:



public static void processFile(String inputFilePath) throws IOException inputFilePath.trim()
.length() == 0)
throw new IllegalArgumentException("Error reading file.");


// Initialize required variables for processing the file
String line;
int count = 0;

// We are reading from the file, so we can use FileReader and InputStreamReader.
try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))

// Read numbers from the line
while ((line = fileReader.readLine()) != null) // Stop reading file when -1 is reached
Scanner scanner = new Scanner(line);

// First input is the start
int start = scanner.nextInt();

if (start == -1)
break;


// Second input is the end
int end = scanner.nextInt();

// Third input is the weight
double weight = scanner.nextDouble();

// do stuff

catch (IOException e)
throw new IOException("Error processing the file.");







share|improve this answer
































    1














    I would start by checking that I can read the file (you can use File.canRead() to do that). Next, I would compile a regular expression with three grouping operations. Then I would use BufferedReader.readLine() to read lines of text; the read() call returns a single character. Then it only remains to parse matching lines. And I see no purpose in swallowing the original exception only to rethrow it (in fact, you lose all stack trace information your current way). Putting that all together,



    public static void processFile(String inputFilePath) throws IOException 
    File f = new File(inputFilePath);
    if (!f.canRead())
    throw new IllegalArgumentException("Error reading file.");


    // Initialize required variables for processing the file
    try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))
    Pattern p = Pattern.compile("^\s*(\d+)\s+(\d+)\s+(\d.+)$");
    String line;
    while ((line = fileReader.readLine()) != null)
    Matcher m = p.matcher(line);
    if (m.matches())
    int start = Integer.parseInt(m.group(1));
    int end = Integer.parseInt(m.group(2));
    double weight = Double.parseDouble(m.group(3));
    System.out.printf("start=%d, end=%d, weight=%.2f%n", start, end, weight);









    share|improve this answer
































      0














      Instead of using read you can just use readLine then use split with your separator being three spaces I think?



       try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) 
      String line;
      while(!(line = fileReader.readLine()).equals("-1"))
      String[] edge = line.split(" ");
      int start = Integer.parseInt(edge[0]);
      int end = Integer.parseInt(edge[1]);
      double weight = Double.parseDouble(edge[2]);

      catch (IOException e)
      e.printStackTrace();






      share|improve this answer



























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55368568%2fhow-to-read-integers-from-a-file-using-bufferedreader-from-java%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        Switch up to readLine and use a Scanner:



        public static void processFile(String inputFilePath) throws IOException inputFilePath.trim()
        .length() == 0)
        throw new IllegalArgumentException("Error reading file.");


        // Initialize required variables for processing the file
        String line;
        int count = 0;

        // We are reading from the file, so we can use FileReader and InputStreamReader.
        try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))

        // Read numbers from the line
        while ((line = fileReader.readLine()) != null) // Stop reading file when -1 is reached
        Scanner scanner = new Scanner(line);

        // First input is the start
        int start = scanner.nextInt();

        if (start == -1)
        break;


        // Second input is the end
        int end = scanner.nextInt();

        // Third input is the weight
        double weight = scanner.nextDouble();

        // do stuff

        catch (IOException e)
        throw new IOException("Error processing the file.");







        share|improve this answer





























          1














          Switch up to readLine and use a Scanner:



          public static void processFile(String inputFilePath) throws IOException inputFilePath.trim()
          .length() == 0)
          throw new IllegalArgumentException("Error reading file.");


          // Initialize required variables for processing the file
          String line;
          int count = 0;

          // We are reading from the file, so we can use FileReader and InputStreamReader.
          try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))

          // Read numbers from the line
          while ((line = fileReader.readLine()) != null) // Stop reading file when -1 is reached
          Scanner scanner = new Scanner(line);

          // First input is the start
          int start = scanner.nextInt();

          if (start == -1)
          break;


          // Second input is the end
          int end = scanner.nextInt();

          // Third input is the weight
          double weight = scanner.nextDouble();

          // do stuff

          catch (IOException e)
          throw new IOException("Error processing the file.");







          share|improve this answer



























            1












            1








            1







            Switch up to readLine and use a Scanner:



            public static void processFile(String inputFilePath) throws IOException inputFilePath.trim()
            .length() == 0)
            throw new IllegalArgumentException("Error reading file.");


            // Initialize required variables for processing the file
            String line;
            int count = 0;

            // We are reading from the file, so we can use FileReader and InputStreamReader.
            try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))

            // Read numbers from the line
            while ((line = fileReader.readLine()) != null) // Stop reading file when -1 is reached
            Scanner scanner = new Scanner(line);

            // First input is the start
            int start = scanner.nextInt();

            if (start == -1)
            break;


            // Second input is the end
            int end = scanner.nextInt();

            // Third input is the weight
            double weight = scanner.nextDouble();

            // do stuff

            catch (IOException e)
            throw new IOException("Error processing the file.");







            share|improve this answer













            Switch up to readLine and use a Scanner:



            public static void processFile(String inputFilePath) throws IOException inputFilePath.trim()
            .length() == 0)
            throw new IllegalArgumentException("Error reading file.");


            // Initialize required variables for processing the file
            String line;
            int count = 0;

            // We are reading from the file, so we can use FileReader and InputStreamReader.
            try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))

            // Read numbers from the line
            while ((line = fileReader.readLine()) != null) // Stop reading file when -1 is reached
            Scanner scanner = new Scanner(line);

            // First input is the start
            int start = scanner.nextInt();

            if (start == -1)
            break;


            // Second input is the end
            int end = scanner.nextInt();

            // Third input is the weight
            double weight = scanner.nextDouble();

            // do stuff

            catch (IOException e)
            throw new IOException("Error processing the file.");








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 27 at 1:46









            Not a JDNot a JD

            1,3971 silver badge12 bronze badges




            1,3971 silver badge12 bronze badges


























                1














                I would start by checking that I can read the file (you can use File.canRead() to do that). Next, I would compile a regular expression with three grouping operations. Then I would use BufferedReader.readLine() to read lines of text; the read() call returns a single character. Then it only remains to parse matching lines. And I see no purpose in swallowing the original exception only to rethrow it (in fact, you lose all stack trace information your current way). Putting that all together,



                public static void processFile(String inputFilePath) throws IOException 
                File f = new File(inputFilePath);
                if (!f.canRead())
                throw new IllegalArgumentException("Error reading file.");


                // Initialize required variables for processing the file
                try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))
                Pattern p = Pattern.compile("^\s*(\d+)\s+(\d+)\s+(\d.+)$");
                String line;
                while ((line = fileReader.readLine()) != null)
                Matcher m = p.matcher(line);
                if (m.matches())
                int start = Integer.parseInt(m.group(1));
                int end = Integer.parseInt(m.group(2));
                double weight = Double.parseDouble(m.group(3));
                System.out.printf("start=%d, end=%d, weight=%.2f%n", start, end, weight);









                share|improve this answer





























                  1














                  I would start by checking that I can read the file (you can use File.canRead() to do that). Next, I would compile a regular expression with three grouping operations. Then I would use BufferedReader.readLine() to read lines of text; the read() call returns a single character. Then it only remains to parse matching lines. And I see no purpose in swallowing the original exception only to rethrow it (in fact, you lose all stack trace information your current way). Putting that all together,



                  public static void processFile(String inputFilePath) throws IOException 
                  File f = new File(inputFilePath);
                  if (!f.canRead())
                  throw new IllegalArgumentException("Error reading file.");


                  // Initialize required variables for processing the file
                  try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))
                  Pattern p = Pattern.compile("^\s*(\d+)\s+(\d+)\s+(\d.+)$");
                  String line;
                  while ((line = fileReader.readLine()) != null)
                  Matcher m = p.matcher(line);
                  if (m.matches())
                  int start = Integer.parseInt(m.group(1));
                  int end = Integer.parseInt(m.group(2));
                  double weight = Double.parseDouble(m.group(3));
                  System.out.printf("start=%d, end=%d, weight=%.2f%n", start, end, weight);









                  share|improve this answer



























                    1












                    1








                    1







                    I would start by checking that I can read the file (you can use File.canRead() to do that). Next, I would compile a regular expression with three grouping operations. Then I would use BufferedReader.readLine() to read lines of text; the read() call returns a single character. Then it only remains to parse matching lines. And I see no purpose in swallowing the original exception only to rethrow it (in fact, you lose all stack trace information your current way). Putting that all together,



                    public static void processFile(String inputFilePath) throws IOException 
                    File f = new File(inputFilePath);
                    if (!f.canRead())
                    throw new IllegalArgumentException("Error reading file.");


                    // Initialize required variables for processing the file
                    try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))
                    Pattern p = Pattern.compile("^\s*(\d+)\s+(\d+)\s+(\d.+)$");
                    String line;
                    while ((line = fileReader.readLine()) != null)
                    Matcher m = p.matcher(line);
                    if (m.matches())
                    int start = Integer.parseInt(m.group(1));
                    int end = Integer.parseInt(m.group(2));
                    double weight = Double.parseDouble(m.group(3));
                    System.out.printf("start=%d, end=%d, weight=%.2f%n", start, end, weight);









                    share|improve this answer













                    I would start by checking that I can read the file (you can use File.canRead() to do that). Next, I would compile a regular expression with three grouping operations. Then I would use BufferedReader.readLine() to read lines of text; the read() call returns a single character. Then it only remains to parse matching lines. And I see no purpose in swallowing the original exception only to rethrow it (in fact, you lose all stack trace information your current way). Putting that all together,



                    public static void processFile(String inputFilePath) throws IOException 
                    File f = new File(inputFilePath);
                    if (!f.canRead())
                    throw new IllegalArgumentException("Error reading file.");


                    // Initialize required variables for processing the file
                    try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath)))
                    Pattern p = Pattern.compile("^\s*(\d+)\s+(\d+)\s+(\d.+)$");
                    String line;
                    while ((line = fileReader.readLine()) != null)
                    Matcher m = p.matcher(line);
                    if (m.matches())
                    int start = Integer.parseInt(m.group(1));
                    int end = Integer.parseInt(m.group(2));
                    double weight = Double.parseDouble(m.group(3));
                    System.out.printf("start=%d, end=%d, weight=%.2f%n", start, end, weight);










                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 27 at 1:55









                    Elliott FrischElliott Frisch

                    160k13 gold badges107 silver badges198 bronze badges




                    160k13 gold badges107 silver badges198 bronze badges
























                        0














                        Instead of using read you can just use readLine then use split with your separator being three spaces I think?



                         try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) 
                        String line;
                        while(!(line = fileReader.readLine()).equals("-1"))
                        String[] edge = line.split(" ");
                        int start = Integer.parseInt(edge[0]);
                        int end = Integer.parseInt(edge[1]);
                        double weight = Double.parseDouble(edge[2]);

                        catch (IOException e)
                        e.printStackTrace();






                        share|improve this answer





























                          0














                          Instead of using read you can just use readLine then use split with your separator being three spaces I think?



                           try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) 
                          String line;
                          while(!(line = fileReader.readLine()).equals("-1"))
                          String[] edge = line.split(" ");
                          int start = Integer.parseInt(edge[0]);
                          int end = Integer.parseInt(edge[1]);
                          double weight = Double.parseDouble(edge[2]);

                          catch (IOException e)
                          e.printStackTrace();






                          share|improve this answer



























                            0












                            0








                            0







                            Instead of using read you can just use readLine then use split with your separator being three spaces I think?



                             try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) 
                            String line;
                            while(!(line = fileReader.readLine()).equals("-1"))
                            String[] edge = line.split(" ");
                            int start = Integer.parseInt(edge[0]);
                            int end = Integer.parseInt(edge[1]);
                            double weight = Double.parseDouble(edge[2]);

                            catch (IOException e)
                            e.printStackTrace();






                            share|improve this answer













                            Instead of using read you can just use readLine then use split with your separator being three spaces I think?



                             try (BufferedReader fileReader = new BufferedReader(new FileReader(inputFilePath))) 
                            String line;
                            while(!(line = fileReader.readLine()).equals("-1"))
                            String[] edge = line.split(" ");
                            int start = Integer.parseInt(edge[0]);
                            int end = Integer.parseInt(edge[1]);
                            double weight = Double.parseDouble(edge[2]);

                            catch (IOException e)
                            e.printStackTrace();







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 27 at 1:53









                            chrischris

                            514 bronze badges




                            514 bronze badges






























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55368568%2fhow-to-read-integers-from-a-file-using-bufferedreader-from-java%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript