Reputation: 151
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.
Upvotes: 14
Views: 46813
Reputation: 724
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()));
}
}
}
Upvotes: 0
Reputation: 533500
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.
Upvotes: 2
Reputation: 33534
Scanner scanner = new Scanner(getClass().getResourceAsInputStream("Words.txt"));
String s = new String();
while(scanner.hasNextLine()){
s = s + scanner.nextLine();
}
Upvotes: 0
Reputation: 19788
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
Upvotes: 2
Reputation: 12837
InputStream is = MyClass.class.getResourceAsStream("Words.txt");
...
Upvotes: 19