I have a .ini file that looks like this and am using ini4j to parse the file:
[Filepath]
Inbound=C:\Users\Bilbo\Desktop\Testing
I want to return that exact string (C:\Users\Bilbo\Desktop\Testing) and I have the following java code:
public static String ParseIniInbound (File iniFile) throws
InvalidFileFormatException, IOException {
String iniFileName = iniFile.toString();
Ini ini = new Ini(new File(iniFileName));
String InboundPath= ini.get("Filepath", "Inbound");
return InboundPath;
}
However, what is returned is C:UsersBilboDesktopTesting
I tried putting quotes around the filepath in the .ini file to read it as a string but that didn't work. I used double slashes (C:\\Users\\Bilbo\\Desktop\\Testing) in the .ini file which returns what im looking for (C:\Users\Bilbo\Desktop\Testing) but I want to be able to just copy and paste a filepath and not have to manually put in double slashes in the .ini flie. Is there a way to read in a string from an .ini file with ini4j or another way around this? Thanks
Easiest way would be to disable escaping.
import org.ini4j.Config;
...
Config.getGlobal().setEscape(false);
Other alternative would be to use the Wini class instead
import org.ini4j.Wini;
...
Wini ini = new Wini(new File(iniFileName));
Just change slash for double slash after reading the file path:
public static String ParseIniInbound (File iniFile) throws
InvalidFileFormatException, IOException {
String iniFileName = iniFile.toString().replaceAll("\\", "\\\\");
Ini ini = new Ini(new File(iniFileName));
String InboundPath= ini.get("Filepath", "Inbound");
return InboundPath;
}
Related
I have a .ini file that looks like this:
[Filepath]
Inbound=C:\Users\Bilbo\Desktop\Testing
I want to return that exact string (C:\Users\Bilbo\Desktop\Testing) and I have the following code:
public static String ParseIniInbound (File iniFile) throws
InvalidFileFormatException, IOException {
String iniFileName = iniFile.toString();
Ini ini = new Ini(new File(iniFileName));
String InboundPath= ini.get("Filepath", "Inbound");
return InboundPath;
}
However, what is returned is C:UsersBilboDesktopTesting
I tried putting quotes around the filepath in the .ini file to read it as a string but that didn't work. I used double slashes (C:\\Users\\Bilbo\\Desktop\\Testing) which returns (C:\Users\Bilbo\Desktop\Testing) but I want to be able to just copy and paste a filepath and not have to manually put in double slashes. Is there a way to read in a string from an .ini file with ini4j or another way around this? Thanks
Well I couldn't find anything about this, except your post so here is my solution, but if this is the intended way it is really dumb.
ini.put("Default_Values", "dWorkflowStart", "C:\\" + "\\User\\" + "\\kh\\" + "\\Desktop\\"
+ "\\workstuff\\" + "\\samples\\" + "\\test_in");
This puts out [Default_Values]
dWorkflowStart = C:\\Users\\kh\\Desktop\\workstuff\\samples\\test_in
My problem is very simple and yet I can't figure out how to solve it.
I have text files in a folder:
"C:/aaa/bbb/ccc/ddd/test.txt"
And excel files in a folder within the text files folder:
"C:/aaa/bbb/ccc/ddd/excelFiles/test.xls"
Both text and excel files have the same name.
I would like to be able to access the path of those excel files.
What I did is:
this.file.getParent()+"\\"+"excelFiles"+"\\"+file.getName().substring(0, fileName.indexOf('.'))+".xls"
I get a "String index out of range" error.
Thank you for your help :)
If I understand your question, one option is to use File.getCanonicalPath() like,
try {
File f = new File("C:/aaa/bbb/ccc/ddd/excelFiles/test.xls");
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
You might want to try this ->
String dynamicExcelFileName = file.getName().substring(0, fileName.indexOf('.'))
into a variable and use it in the path for accessing the excel file.
this way you get to be extra sure to check if the path is properly captured in variable or not and thus less chances of getting index out of range error.
plus the code is more readable
Looking at your snippet, I can see that you're accessing the file's name in two different ways:
file.getName().substring(...)
and
fileName.indexOf(...).
Are you sure that fileName is not empty when you try to determine the index of the dot?
this.file.getParent()+"\"+"excelFiles"+"\"+file.getName().substring(0, this.file.getName().indexOf('.'))+".xls"
This could be achieved quite easily, even without using existing libraries like FileUtils.
These three method can create the corresponding Excel File object for your text object
private File getExcelFile(final File txtFile) throws IOException {
final String path = txtFile.getCanonicalPath();
final String directory = path.substring(0, path.lastIndexOf(System.getProperty("file.separator")));
return new File(getExcelSubdirectory(directory), getExcelFilename(txtFile.getName()));
}
private File getExcelSubdirectory(final String parent) {
return new File(parent, "excelFiles");
}
private static String getExcelFilename(final String filename) {
return filename.substring(0, filename.lastIndexOf('.')) + ".xls";
}
If you use them like this:
File txt = new File("C:/aaa/bbb/ccc/ddd/test.txt");
System.out.println(txt.getCanonicalPath());
File excel = getExcelFile(txt);
System.out.println(excel.getCanonicalPath());
.. it will print:
C:\aaa\bbb\ccc\ddd\test.txt
C:\aaa\bbb\ccc\ddd\excelFiles\test.xls
In Eclipse, when I right click on the file I want to input from in my project, it shows two things:
path: /SWT/src/data.txt
location: C:\Users\Yoshikawa\workspace\SWT\src\data.txt
Is there any way I can get the location (C:\Users\Yoshikawa\workspace\SWT\src\data.txt) is I know just the path (/SWT/src/data.txt) ?
Ex.
public String ReadFile(String file_path) {
//Search current project directory
return file_location
}
public String readFile(String file_path){
File f = new File(file_path);
return f.getAbsolutePath();
}
You attempt to create a File object based on the file_path and then run the method getAbsolutePath() method of the File class.
h
You can read up more on this here: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
Hopefully this works.
Take a look at the Java Path Class.
You can use File.getAbsolutePath or File.getCanonicalPath. They are not the same, see the difference
String relativePath = "../1.txt";
System.out.println(new File(relativePath).getCanonicalPath());
System.out.println(new File(relativePath).getAbsolutePath());
output
D:\workspace1\1.txt
D:\workspace1\x\..\1.txt
see java.io.File API for details
I have a properties file contains the file name only say file=fileName.dat. I've put the properties file under the class path and could read the file name(file.dat) properly from it in the mainClass. After reading the file name I passed the file name(just name not the path) to another class under a package say pack.myClass to read that file. But the problem is pack.myClass could not get the file path properly. I've put the file fileName.dat both inside and outside the packagepack but couldn't make it work.
Can anybody suggest me that where to put the file fileName.dat so I can read it properly and the whole application would be portable too.
Thanks!
The code I'm using to read the config file and getting the file name:
Properties prop = new Properties();
InputStream in = mainClass.class.getResourceAsStream("config.properties");
prop.load(in);
in.close();
myClass mc = new myClass();
mc.readTheFile(prop.getProperty("file"));
/*until this code is working good*/
Then in myClass which is under package named pack I am doing:
public void readTheFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename); /*this couldn't get the file whether i'm putting the file inside or outside the package folder */
/*after reading the file I've to do the BufferReader for further operation*/
BufferedReader bufferedReader = new BufferedReader(fileReader);
I assume that you are trying to read properties file using getResource method of class. If you put properties file on root of the classpath you should prefix file name with '/' to indicate root of classpath, for example getResource("/file.dat"). If properties file is under the same folder with the class you on which you invoke getResource method, than you should not use '/' prefix.
When you use a relative file name such as fileName.dat, you're asking for a file with this name in the current directory. The current directory has nothing to do with packages. It's the directory from which the JVM is started.
So if you're in the directory c:\foo\bar when you launch your application (using java -cp ... pack.MyClass), it will look for the file c:\foo\bar\fileName.dat.
Try..
myClass mc = new myClass();
InputStream in = mc.getClass().getResourceAsStream("/pack/config.properties");
..or simply
InputStream in = mc.getClass().getResourceAsStream("config.properties");
..for the last line if the main is in myClass The class loader available in the main() will often be the bootstrap class-loader, as opposed to the class-loader intended for application resources.
Class.getResource will look in your package directory for a file of the specified name.
JavaDocs here
Or getResourceAsStream is sometimes more convenient as you probably want to read the contents of the resource.
Most of the time it would be best to look for the "fileName.dat" somewhere in the "user.home" folder, which is a system property. First create a File path from the "user.home" and then try to find the file there. This is a bit of a guess as you don't provide the exact user of the application, but this would be the most common place.
You are currently reading from the current folder which is determined by
String currentDir = new File(".").getAbsolutePath();
or
System.getProperty("user.dir")
To read a file, even from within a jar archive:
readTheFile(String package, String filename) throws MalformedURLException, IOException
{
String filepath = package+"/"+filename;
// like "pack/fileName.dat" or "fileName.dat"
String s = (new SourceBase()).getSourceBase() + filepath;
URL url = new URL(s);
InputStream ins = url.openStream();
BufferedReader rdr = new BufferedReader(new InputStreamReader(ins, "utf8"));
do {
s = rdr.readLine();
if(s!= null) System.out.println(s);
}
while(s!=null);
rdr.close();
}
with
class SourceBase
{
public String getSourceBase()
{
String cn = this.getClass().getName().replace('.', '/') + ".class";
// like "packagex/SourceBase.class"
String s = this.getClass().getResource('/' + cn).toExternalForm();
// like "file:/javadir/Projects/projectX/build/classes/packagex/SourceBase.class"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/
// testProject.jar!/px/SourceBase.class"
return s.substring(0, s.lastIndexOf(cn));
// like "file:/javadir/Projects/projectX/build/classes/"
// or "jar:file:/opt/java/PROJECTS/testProject/dist/testProject.jar!/"
}
}
I am trying to read a text file which is set in CLASSPATH system variable. Not a user variable.
I am trying to get input stream to the file as below:
Place the directory of file (D:\myDir) in CLASSPATH and try below:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");
Place full path of file (D:\myDir\SomeTextFile.txt) in CLASSPATH and try the same above 3 lines of code.
But unfortunately NONE of them are working and I am always getting null into my InputStream in.
With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either of:
// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
If those aren't working, that suggests something else is wrong.
So for example, take this code:
package dummy;
import java.io.*;
public class Test
{
public static void main(String[] args)
{
InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}
And this directory structure:
code
dummy
Test.class
txt
SomeTextFile.txt
And then (using the Unix path separator as I'm on a Linux box):
java -classpath code:txt dummy.Test
Results:
true
true
When using the Spring Framework (either as a collection of utilities or container - you do not need to use the latter functionality) you can easily use the Resource abstraction.
Resource resource = new ClassPathResource("com/example/Foo.class");
Through the Resource interface you can access the resource as InputStream, URL, URI or File. Changing the resource type to e.g. a file system resource is a simple matter of changing the instance.
This is how I read all lines of a text file on my classpath, using Java 7 NIO:
...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
...
Files.readAllLines(
Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());
NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.
Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets
(these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").
Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8
Please try
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
Your tries didn't work because only the class loader for your classes is able to load from the classpath. You used the class loader for the java system itself.
To actually read the contents of the file, I like using Commons IO + Spring Core. Assuming Java 8:
try (InputStream stream = new ClassPathResource("package/resource").getInputStream()) {
IOUtils.toString(stream);
}
Alternatively:
InputStream stream = null;
try {
stream = new ClassPathResource("/log4j.xml").getInputStream();
IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
}
To get the class absolute path try this:
String url = this.getClass().getResource("").getPath();
Somehow the best answer doesn't work for me. I need to use a slightly different code instead.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("SomeTextFile.txt");
I hope this help those who encounters the same issue.
If you use Guava:
import com.google.common.io.Resources;
we can get URL from CLASSPATH:
URL resource = Resources.getResource("test.txt");
String file = resource.getFile(); // get file path
or InputStream:
InputStream is = Resources.getResource("test.txt").openStream();
Ways to convert an InputStream to a String
To read the contents of a file into a String from the classpath, you can use this:
private String resourceToString(String filePath) throws IOException, URISyntaxException
{
try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath))
{
return IOUtils.toString(inputStream);
}
}
Note:
IOUtils is part of Commons IO.
Call it like this:
String fileContents = resourceToString("ImOnTheClasspath.txt");
You say "I am trying to read a text file which is set in CLASSPATH system variable." My guess this is on Windows and you are using this ugly dialog to edit the "System Variables".
Now you run your Java program in the console. And that doesn't work: The console gets a copy of the values of the system variables once when it is started. This means any change in the dialog afterwards doesn't have any effect.
There are these solutions:
Start a new console after every change
Use set CLASSPATH=... in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog.
Put the call to Java into .BAT file and double click it. This will create a new console every time (thus copying the current value of the system variable).
BEWARE: If you also have a User variable CLASSPATH then it will shadow your system variable. That is why it is usually better to put the call to your Java program into a .BAT file and set the classpath in there (using set CLASSPATH=) rather than relying on a global system or user variable.
This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths.
My answer is not exactly what is asked in the question. Rather I am giving a solution exactly how easily we can read a file into out java application from our project class path.
For example suppose a config file name example.xml is located in a path like below:-
com.myproject.config.dev
and our java executable class file is in the below path:-
com.myproject.server.main
now just check in both the above path which is the nearest common directory/folder from where you can access both dev and main directory/folder (com.myproject.server.main - where our application’s java executable class is existed) – We can see that it is myproject folder/directory which is the nearest common directory/folder from where we can access our example.xml file. Therefore from a java executable class resides in folder/directory main we have to go back two steps like ../../ to access myproject. Now following this, see how we can read the file:-
package com.myproject.server.main;
class Example {
File xmlFile;
public Example(){
String filePath = this.getClass().getResource("../../config/dev/example.xml").getPath();
this.xmlFile = new File(filePath);
}
public File getXMLFile() {
return this.xmlFile;
}
public static void main(String args[]){
Example ex = new Example();
File xmlFile = ex.getXMLFile();
}
}
If you compile your project in jar file:
you can put your file in resources/files/your_file.text or pdf;
and use this code:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class readFileService(){
private static final Logger LOGGER = LoggerFactory.getLogger(readFileService.class);
public byte[] getFile(){
String filePath="/files/your_file";
InputStream inputStreamFile;
byte[] bytes;
try{
inputStreamFile = this.getClass().getResourceAsStream(filePath);
bytes = new byte[inputStreamFile.available()];
inputStreamFile.read(bytes);
} catch(NullPointerException | IOException e) {
LOGGER.error("Erreur read file "+filePath+" error message :" +e.getMessage());
return null;
}
return bytes;
}
}
I am using webshpere application server and my Web Module is build on Spring MVC. The Test.properties were located in the resources folder, i tried to load this files using the following:
this.getClass().getClassLoader().getResourceAsStream("Test.properties");
this.getClass().getResourceAsStream("/Test.properties");
None of the above code loaded the file.
But with the help of below code the property file was loaded successfully:
Thread.currentThread().getContextClassLoader().getResourceAsStream("Test.properties");
Thanks to the user "user1695166".
Use org.apache.commons.io.FileUtils.readFileToString(new File("src/test/resources/sample-data/fileName.txt"));
Don't use getClassLoader() method and use the "/" before the file name. "/" is very important
this.getClass().getResourceAsStream("/SomeTextFile.txt");
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile
{
/**
* * feel free to make any modification I have have been here so I feel you
* * * #param args * #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// thread pool of 10
File dir = new File(".");
// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}
}
you have to put your 'system variable' on the java classpath.