简体   繁体   中英

Convert ArrayList<String> With Quotes Read from an external txt file to ArrayList<String> Without the Quotes Using Java 8

I am trying to read huge lines of words in quotes eg "DSRD","KJHT","BFXXX","OUYTP" from a text file, so that I can have something like [DSRD, KJHT, BFXXX, OUYTP].

I have tried these 2 codes below but still returns the lines with quotes:

   1. List<String> lines = Files.readAllLines(Paths.get(filePath), ENCODING);
   2. List<String> lines = new ArrayList<>(Files.readAllLines(Paths.get(filePath)));

Is there a way I can make this return just the list of the Strings without the quotes in each of the Strings?

Any help would be greatly appreciated.

Thanks

You can remove the quotes after reading the file using String#replaceAll :

List<String> lines = Files.readAllLines(Paths.get(filePath), ENCODING);
lines = lines.stream().map(s -> s.replaceAll("\"", "")).collect(Collectors.toList());

You can split the words as they are separated by commas and apply transformation on them and finally join them back:

for(int i = 0; i < lines.size(); i++) {
    String line = lines[i];
    String[] words = line.split(",");

    for (int j = 0; j < words.length; j++) {
        words[j] = words[j].replaceAll("^\"|\"$", "");
    }
    
    lines[i] = String.join(",", words);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM