Search code examples
javaarraysfilesplitdelimiter

How do you split at the end of the line in Java?


I have a .txt file that looks like this:

Event=ThermostatNight,time=0
Event=LightOn,time=2000
Event=WaterOff,time=10000
Event=ThermostatDay,time=12000
Event=Bell,time=9000,rings=5
Event=WaterOn,time=6000
Event=LightOff,time=4000
Event=Terminate,time=20000
Event=FansOn,time=7000
Event=FansOff,time=8000

I'm trying to store the above into an array, for example the array should be:

[0] = Event
[1] = ThermostatNight
[2] = time
[3] = 0
[4] = Event
[5] = LightOn
[6] = time
[7] = 2000
//.... etc

Basically I'm trying to store the event name as a variable and the time as another variable and using = and , as split points. However, at index [3] shows "0Event" and index [6] shows "2000Event", etc.

I'm not sure if I should be using a new line as a split point or white space, or I might just be looking at this the wrong way. Here is my code:

public static void main(String[] args) {

try {
    
Scanner content = new Scanner(new File("file.txt")).useDelimiter(",");

StringBuilder sb = new StringBuilder();
    
while(content.hasNext()) {
    sb.append(content.nextLine());
        }

String[] wordsArray = sb.toString().split("[=,]");

//Test what is at each index
System.out.println(wordsArray[3]);          
}
    
catch (FileNotFoundException e) {
    e.printStackTrace();
}

}

I've been playing around with String[] wordsArray = sb.toString().split("[=,]"); and have tried modifying the code to:

.split("\[=,\\n\]")
.split("\[=,\\s\]")
.split("\[=,\\n\]")
...etc

and many other different arguments inside of .split.

But I still keep getting index [3] and [6] as 0Event and 2000Event.

Again not sure if I might just be looking at this the wrong way or taking the wrong approach. Any help is greatly appreciated.


Solution

  • "... I'm trying to store the above into an array ..."

    "... I'm not sure if I should be using a new line as a split point or white space, or I might just be looking at this the wrong way ..."

    There are several ways to accomplish this task.

    You can add more values to the Scanner#useDelimiter call, and then use next, instead of nextLine.

    \r\n?|\n|[,=]
    

    This will allow you to get rid of the StringBuilder.
    And for the wordsArray, use a List initially, and convert to an array when needed.

    try {
    
    Scanner content = new Scanner(new File("file.txt")).useDelimiter("\r\n?|\n|[,=]");
    
    List<String> list = new ArrayList<>();
    
    while(content.hasNext()) {
        list.add(content.next());
            }
    
    String[] wordsArray = list.toArray(new String[0]);
    
    //Test what is at each index
    System.out.println(wordsArray[3]);
    }
    
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    

    Or, use the Scanner as is, without a modified delimiter, and use the String#split method.

    while(content.hasNextLine())
        wordsArray.addAll(List.of(content.nextLine().split("[,=]")));
    
    try {
    
    Scanner content = new Scanner(new File("file.txt"));
    
    List<String> list = new ArrayList<>();
    
    while(content.hasNext()) {
        list.addAll(List.of(content.nextLine().split("[,=]")));
            }
    
    String[] wordsArray = list.toArray(new String[0]);
    
    //Test what is at each index
    System.out.println(wordsArray[3]);
    }
    
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    

    Output

    0
    

    "... Again not sure if I might just be looking at this the wrong way or taking the wrong approach. Any help is greatly appreciated."

    Instead of Scanner, you can use the BufferedReader class, which offers the lines method.

    try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
        List<String> list = reader.lines()
                                  .flatMap(x -> Stream.of(x.split("[,=]")))
                                                      .toList();
    }