0

I have built a Spring boot MVC application with a Tree data structure in place of an actual database. The program reads from a text file and stores words in the tree. originally I used a the CommandLineRunner class to populate the tree, which works... but after creating a fat jar and running the jar, I get a file not found exception. how can I build a fat jar with maven that includes the text file with maven?

the file is currently in the project root.

here is the logic to generate the tree:

@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GenerateTree implements CommandLineRunner {

@Autowired
TreeRepository trie = new TreeRepository();

@Autowired
FileReader fileReader = new FileReader();


@Override
public void run(String... args) throws Exception {

    for (String s : fileReader.readFile("wordList1.txt")){
        trie.add(s);
    }
}
}

here is the logic that reads in the file:

@Component
public class FileReader {

List<String> readFile(String filename){
    List<String> list = new ArrayList<>();
    try (Stream<String> stream = Files.lines(Paths.get(filename))) {
        list = stream
                .filter(line -> line.matches("[a-zA-Z]+"))
                .collect(Collectors.toList());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return list;
}
}
StillLearningToCode
  • 2,271
  • 4
  • 27
  • 46

1 Answers1

0

You cannot access a File inside a jar (see https://stackoverflow.com/a/8258308/4516887). Put the wordlist.txt into the src/main/resources directory and read its contents using a [ClassPathResource][1]:

ClassPathResource resource = new ClassPathResource("worldlist.txt");
try (InputStream in = resource.getInputStream();
     BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {

    String line;
    while((line = reader.readLine()) != null) {
        ...
    }
}
Community
  • 1
  • 1
fateddy
  • 6,887
  • 3
  • 22
  • 26