Trouble getting file path in Netbeans project - java

I'm making a program that uses text files. I need to make it so that the program can be run from a different computer using its jar file. The problem is that I can't get it to find the right file path to the text files. I've tried using getResource(), but it's still not working right. Here's the code:
public class Params {
public static void init() {
hsChartSuited = new int[13][13];
file = new File(Params.class.getResource("HandStrengthDataSuited.txt").getFile());
try {
Scanner input = new Scanner(file);
for (int i = 0; i < hsChartSuited.length; i++) {
for (int j = 0; j < hsChartSuited[i].length; j++) {
hsChartSuited[i][j] = Integer.parseInt(input.next()) - 20;
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
HandStrengthDataSuited.txt is a file that is in the src folder for my project. It's also located outside of the folder, in the project's main directory as well. I've tried printing the absolute file path, and this is what I get:
/Users/MyUsername/file:/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/dist/HoldEm.jar!/holdem/HandStrengthDataSuited.txt
The file path that I need to get is
/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/holdem/HandStrengthDataSuited.txt
Does anyone know what the problem is here?

If your files is in src folder,
class Tools {
public static InputStream getResourceAsStream(String resource)
throws FileNotFoundException
{
String stripped = resource.startsWith("/") ? resource.substring(1) : resource;
InputStream stream = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader != null) {
stream = classLoader.getResourceAsStream(stripped);
}
if (stream == null) {
stream = Tools.class.getResourceAsStream(resource);
}
if (stream == null) {
stream = Tools.class.getClassLoader().getResourceAsStream(stripped);
}
if (stream == null) {
throw new FileNotFoundException("Resource not found: " + resource);
}
return stream;
}
}
Use:
reader = new BufferedReader(new InputStreamReader(getResourceAsStream("org/paulvargas/resources/file.txt"), "UTF-8"));

Related

How can i get all file names in resources directory in gradle project?

Below code, i am manually write "a.json", "b.json".
But i want to get all file names in resources directory and
is it possible?
public static void loadFiles() throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
List<String> fileNames = List.of("a.json", "b.json"); // Bad
// List<String> fileNames = getFileNamesInResources(); // Good
for (int i = 0; i < fileNames.size(); i++) {
String fileName = fileNames.get(i);
InputStream is = classLoader.getResourceAsStream(fileName);
String content = new String(is.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(content);
is.close();
}
}

FileReader doesn't read file in tomcat Server

i have this code
public ArrayList<String> getMail() {
ArrayList<String> i = new ArrayList();
try {
int j = 0 ;
FileReader file = new FileReader("emaillist0.txt");
BufferedReader lerArq = new BufferedReader(file);
String linha = lerArq.readLine();
System.out.println("tp aqio ´prra");
while (linha != null) {
i.add(j, linha);
j++;
linha = lerArq.readLine();
}
System.out.println(i.size());
file.close();
return i;
} catch (IOException e) {
System.err.printf( e.getMessage());
return null;
}
}
this problem is when i execute this code in apache tomcat throws this error
emaillist0.txt (The system cannot find the file specified)java.lang.NullPointerException
but when i execute this code in a java application work perfectly
use absolute path instead of file's name, or move your file into bin directory of tomcat (of course it depends on your OS)

Java - Create Zip-file with multiple files from different locations with subfolders

I am trying to generate a zip file in Java, that contains several files of different types (e.g. images, fonts etc) that are lying in different locations. Furthermore I want the zip file to have subfolders where the files are put by their type (e.g. images should go to the images folder within the zip.
These are the files that I have (each can be in a different location):
index.html
img1.jpg
img2.jpg
font1.woff
font2.woff
style.css
custom.js
And this is how they should be in the zip file:
index.html
images/img1.jpg
images/img2.jpg
fonts/font1.woff
fonts/font2.woff
js/custom.js
css/styles.css
So far I have managed to take one file in a specific path and prompt the user for the output location. A zip-file will be generated with the file that is specified in the input. Here is the code I have so far:
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Speicherort auswählen");
int userSelection = fileChooser.showSaveDialog(parentFrame);
String pathToFile;
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
print(fileToSave.getAbsolutePath());
pathToFile = fileToSave.getAbsolutePath();
}
pathToFile = pathToFile.replace("\\", "/");
String outFileName = pathToFile;
String inFileName = "C:/Users/asoares/Desktop/mobio_export_test/index.html";
ZipOutputStream zos = null;
FileInputStream fis = null;
try {
zos = new ZipOutputStream(new FileOutputStream(outFileName));
fis = new FileInputStream(inFileName);
zos.putNextEntry(new ZipEntry(new File(inFileName).getName()));
int len;
byte[] buffer = new byte[2048];
while((len = fis.read(buffer, 0, buffer.length)) > 0) {
zos.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {}
}
if(zos != null){
try {
zos.closeEntry();
zos.close();
} catch (IOException e) {}
}
}
I would be really glad if someone can help me!!!
It should work like this.
The zip directory name should at best be created by another method (there are more image types than jpg :)).
public static Path zip(List<Path> files, Path zipFileTarget) throws IOException {
try (FileOutputStream fos = new FileOutputStream(zipFileTarget.toFile());
ZipOutputStream zos = new ZipOutputStream(fos)) {
if (!Files.exists(zipFileTarget))
Files.createFile(zipFileTarget);
createEntries(files, zos);
zos.close();
return zipFileTarget;
}
}
private static List<String> createEntries(List<Path> files, ZipOutputStream zos) throws IOException {
List<String> zippedFiles = new ArrayList<>();
Matcher matcherFileExt = Pattern.compile("^.*\\.([^.]+)$").matcher("");
for (Path f : files) {
if (Files.isRegularFile(f)) {
String fileName = f.getFileName().toString();
String fileExt = matcherFileExt.reset(fileName).matches()
? matcherFileExt.replaceAll("$1")
: "unknown";
// You should determine the dir name with a more sophisticated
// approach.
String dir;
if (fileExt.equals("jpg")) dir = "images";
else if (fileExt.equals("woff")) dir = "fonts";
else dir = fileExt;
zos.putNextEntry(new ZipEntry(dir + "/" + fileName));
Files.copy(f, zos);
zippedFiles.add(fileName);
}
}
return zippedFiles;
}
Edit: this approach works with java 1.7+. You can easily convert a File object to a Path object by calling its toPath() method.

Read specific property from a property file in a jar

I need to read the property "product.build.number" from the property file "version.properties" which lies at the root level of each of the jars. My naive approach is:
private static int getProductBuildNumber(File artefactFile) throws FileNotFoundException, IOException
{
try (ZipInputStream zip = new ZipInputStream(new FileInputStream(
artefactFile)))
{
Set<String> possClasses = new HashSet<>();
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip
.getNextEntry())
{
if (!entry.isDirectory() && entry.getName().toLowerCase().equals(
"version.properties"))
{
List<String> lines = IOUtils.readLines(zip, (String) null);
for (String line : lines)
{
if (line.startsWith("product.build.number"))
{
String[] split = line.split("=");
if (split.length == 2)
{
return Integer.parseInt(split[1]);
}
}
}
}
}
}
throw new IOException("product.build.number not found.");
}
I guess there are more elegant and reliable ways. Any ideas?
Try something like (untested):
private static int getProductBuildNumber(Path artefactFilePath) throws IOException{
try(FileSystem zipFileSystem = FileSystems.newFileSystem(artefactFilePath, null)){
Path versionPropertiesPath = zipFileSystem.getPath("/version.properties");
Properties versionProperties = new Properties();
try (InputStream is = Files.newInputStream(versionPropertiesPath)){
versionProperties.load(is);
}
return Integer.parseInt(versionProperties.getProperty("product.build.number"));
}
}
You haven’t said whether the .jar files are are in your classpath.
If they are in your classpath, you should be using Class.getResourceAsStream to read the entry:
try (InputStream propStream = getClass().getResourceAsStream("/version.properties")) {
// ...
}
If they .jar files are not in your classpath, you should create a jar: URL from the file. The format of such a URL is described in the JarURLConnection documentation.
Note that java.io.File is obsolete, and you should always use Path instead:
private static int getProductBuildNumber(Path artefactFile)
throws IOException {
URL propsURL = new URL("jar:" + artefactFile.toUri() + "!/version.properties");
try (InputStream propStream = propsURL.openStream()) {
// ...
}
}
Regardless of the data’s location, you should always use the Properties class to read properties. (Parsing a properties file yourself means you have to account for comments, Unicode escapes, continuation lines, and all possible name/value separators.)
Properties props = new Properties();
try (InputStream propStream = getClass().getResourceAsStream("/version.properties")) {
props.load(propStream);
}
int buildNumber = Integer.parseInt(
props.getProperty("product.build.number"));

Java - Read all .txt files in folder

Let's say, I have a folder called maps and inside maps I have map1.txt, map2.txt, and map3.txt. How can I use Java and the BufferReader to read all of the .txt files in folder maps (if it is at all possible)?
Something like the following should get you going, note that I use apache commons FileUtils instead of messing with buffers and streams for simplicity...
File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
String content = FileUtils.readFileToString(file);
/* do somthing with content */
}
}
I would take #Andrew White answer (+1 BTW) one step further, and suggest you would use FileNameFilter to list only relevant files:
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
String content = FileUtils.readFileToString(file);
// do something with the file
}
final File folder = new File("C:/Dev Tools/apache-tomcat-6.0.37/webapps/ROOT/somefile");
for (final File fileEntry : folder.listFiles()) {
System.out.println("FileEntry Directory "+fileEntry);
With NIO you can do the following:
Files.walk(Paths.get("/path/to/files"))
.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".txt"))
.map(FileUtils::readFileToString)
// do something
To read the file contents you may use Files#readString but, as usual, you need to handle IOException inside lambda expression.
I think it's good way to read all .txt files from maps and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}
If you want a better way of doing this using the new java.nio api, then this is the way, taken from the java docs
Path dir = ...;
try (DirectoryStream<Path> stream =
Files.newDirectoryStream(dir, "*.txt")) {
for (Path entry: stream) {
System.out.println(entry.getFileName());
}
} catch (IOException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can // only be thrown by newDirectoryStream.
System.err.println(x);
}
Using only JDK, If all your files are in one directory:
File dir = new File("path/to/files/");
for (File file : dir.listFiles()) {
Scanner s = new Scanner(file);
// do something with file
s.close();
}
To exclude files, you can use listFiles(FileFilter)

Categories

Resources