0

My input file is as follows:

 p edge 200 527 
 e 1 2
 e 1 3
 e 1 4 
 e 1 5

The output file should be:

 p edge 200 527 
 e 0 1
 e 0 2
 e 0 3 
 e 0 4

Apart of the first line i should decrease every integer by 1.

What i did:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Example {
   public static String pathToTheGraphFile = "C:\\Users\\Desktop\\inputFile.txt";
   public static void main( String[] args ) throws IOException {
      Path path = Paths.get(pathToTheGraphFile );
      try (Stream<String> stream = Files.lines(path);FileWriter fileWriter = new FileWriter("C:\\Users\\Desktop\\outputFile.txt");) {
         stream.skip(1)
         .map(line-> line.split(" "))
         .map(line -> {
            int a = Integer.parseInt(line[1])-1;
            int b = Integer.parseInt(line[2])-1;
            return new String(line[0]+" "+a+" "+b);
         })
         .forEachOrdered(l-> {
            try {
               fileWriter.write(l);
            } catch (IOException e) {
               e.printStackTrace();
            } 
         });
      }
   }
}

How can I read the first line individually? Because I need to store those information in line 1. For that I skipped the first line, but I should not do it.

As you can see even if the program works well, the readability in my opinion is worse. Is here any suggestion?

kit
  • 1,166
  • 5
  • 16
  • 23
xmen-5
  • 1,806
  • 1
  • 23
  • 44

1 Answers1

2

For the first question, you can use the findFirst() method.

Be aware that the findFirst() method returns an optional.

Edit : Oops deleted half my post somehow.

Do not read from the inputFile and output to an outputFile at the same time. As you said it's poor readability and a function should have one function. You could save your inputFile stream into an array using collect, and then output into a stream again :

Stream<String> stream = Arrays.stream(arrayOfStrings);

To be able to write to an output file using a stream, refer to this answer.

John Kim
  • 1,081
  • 10
  • 26