'Java - Getting file from same package
If I want to read from "Words.txt" which is in the same package as the class, how would I do this? Doing simply Scanner = new Scanner(new File("Words.txt"));
returns an error.
Solution 1:[1]
InputStream is = MyClass.class.getResourceAsStream("Words.txt");
...
Solution 2:[2]
Scanner = new Scanner(new File("/path/to/Words.txt"));
The argument in the File() constructor, Is the path relative to the system your VM is running on, it s doesn't depend on the classe's package.
If you your words.txt is a resource packaged with your war you can see here : Load resource from anywhere in classpath
Solution 3:[3]
Assuming the text file is in the same directory as the .class
, rather than the .java
file you can do
Scanner scanner = new Scanner(getClass().getResourceAsStream("Words.txt"));
What you have will look for the file in the current working directory. When you are building your program this is typically the root directory of your program. When you run it as a standalone program it is usually the directory the program was started from.
Solution 4:[4]
Scanner scanner = new Scanner(getClass().getResourceAsInputStream("Words.txt"));
String s = new String();
while(scanner.hasNextLine()){
s = s + scanner.nextLine();
}
Solution 5:[5]
All the above solutions did not work for me, however this seemed to work as expected even when the source code is exported as a docker image.
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.ClassPathResource;
public class FileUtil {
private static final Logger LOGGER = Logger.getLogger(FileUtil.class.getSimpleName());
private FileUtil() {
// Private constructor
}
private static FileUtil instance = null;
public static FileUtil getInstance() {
if (instance == null) {
instance = new FileUtil();
}
return instance;
}
/**
* Read file from the the resources folder as a string from an
* {@link InputStream}
*
* @param fileName: This can be name.txt or any file format of your choice
* @return
* @throws Exception
*/
public String getResourceFileAsString(String fileName) throws ValidationFailedException {
try {
fileName = String.format("classpath:%s", fileName);
try (InputStream reader = new ClassPathResource(fileName).getInputStream()) {
return IOUtils.toString(reader, StandardCharsets.UTF_8.toString());
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, String.format("Failed to read template {%s}", e.getMessage()), e);
throw new Exception(String.format("Failed to read template {%s}", e.getMessage()));
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jiri Kremser |
Solution 2 | Community |
Solution 3 | |
Solution 4 | Kumar Vivek Mitra |
Solution 5 |