Why do I get NoSuchFileException when using multipartFile @Async in java spring boot?

118 views Asked by At

I can use multipartFile.getInputStream() with the scanner without using @Async, but when I get the file with the multipartFile.getInputStream() stream , it says the file path incorrectly(with @Async).

MultipartFileReader : File stududentId.txt does not have valid content!

error

java.nio.file.NoSuchFileException

@Component
@Slf4j
public class MultipartFileReader {
     public List<String> read(MultipartFile multipartFile) throws IOException {
         List<String> readLineList = new ArrayList<>();

         try {
             Scanner myReader = new Scanner(multipartFile.getInputStream());

StudentService.java

  @Async
     public void workStudent(StudentData studentData) throws IOException {
...
List<Long> studentIdList = multipartFileReader.read(studentData.getstudentIdFile()).stream()
                     .map(Long::parseLong).toList();
1

There are 1 answers

1
Yury Fomichev On

I assume you are getting NoSuchFileException working with local file in async because your program starts new thread and it trying to set input stream.

To fix it you can upload file in local storage (f.e.) and read it from it or read file into byte array, then pass byte array into async method.