0

So I have an input file of the form:

AdjGraphHeader
11
20
30
.
.
.

and I need to create a string array that holds each line separately. So I read the file using:

String s = FileUtils.readFileToString(f);
Words w = new Words(s, (long)s.length());

and then the words constructor did the following:

public Words(String str, long n_) {
    strings = str.split("\\n");
    string = str;
    n = n_;
    m = strings.length;
}

The issue seems to be that there is an extra line at the end of adjGraphHeader, but I have no idea how to get rid of it. Any help would be greatly appreciated.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Lance Strait
  • 4,001
  • 4
  • 17
  • 18

1 Answers1

1

I suspect that your lines are separated not by \n but by \r\n so if you remove \n you still have \r after each word and while printing it you will see empty line. One of solutions could be splitting using this regular expression

"\r?\n|\r" - ? makes element described before it optional, | represent "or" operator

which will handle line separators if forms \r \r\n \n.

You can also use something IMHO simpler like

List<String> lines = Files.readAllLines(Paths.get("locationOfFile"));

or if you already have File f

List<String> lines = Files.readAllLines(f.toPath());

and store each line in list (you can later convert this list to array if you really need it)

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269