Skip to content

Instantly share code, notes, and snippets.

@smallsong
Created August 3, 2018 01:57
Show Gist options
  • Save smallsong/26bbedaff6eae6826e8a4f68b7463ee7 to your computer and use it in GitHub Desktop.
Save smallsong/26bbedaff6eae6826e8a4f68b7463ee7 to your computer and use it in GitHub Desktop.
springboot read resoures file
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import java.io.*;
@Component
public class FileReaderHelper {
public String readToString(String fileName) {
String encoding = "UTF-8";
try {
File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + fileName);
//File file = new File(fileName);
Long fileLength = file.length();
byte[] fileContent = new byte[fileLength.intValue()];
FileInputStream in = new FileInputStream(file);
in.read(fileContent);
in.close();
return new String(fileContent, encoding);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment