Skip to content

Instantly share code, notes, and snippets.

@berinle
Created March 15, 2023 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berinle/1767039e51ae49690f976016fee1b710 to your computer and use it in GitHub Desktop.
Save berinle/1767039e51ae49690f976016fee1b710 to your computer and use it in GitHub Desktop.
sample showing how to read from classpath in JAR
package com.example.foobar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
@RestController
@RequestMapping("/foo")
public class FooController {
// https://www.baeldung.com/spring-classpath-file-access
@Autowired
ResourceLoader resourceLoader;
@GetMapping
public ResponseEntity<?> random() {
List<String> a = new ArrayList<>();
Random rand = new Random();
try {
Resource resource = resourceLoader.getResource("classpath:mikey/my-config.txt");
InputStream is = resource.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
// System.out.println(line);
a.add(line);
}
// Close the file
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
int index = rand.nextInt(a.size());
String s = a.get(index);
return ResponseEntity.ok(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment