Created
March 15, 2023 23:04
-
-
Save berinle/1767039e51ae49690f976016fee1b710 to your computer and use it in GitHub Desktop.
sample showing how to read from classpath in JAR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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