How to use classpath to specify a file location? - java

Here is the structure of my maven project:
main and test folders are under src folder, java and resources folders are under main folder,
in the resources folder, there is a csv file ready for reading.
src
--main
|-- java
|-- resources
|-- test.csv
test
As far as I know,
InputStream file = ClassLoader.getSystemResourceAsStream("test.csv");
could get the file content in the resources file.
However, in order to read and parse csv file based on supercsv library, I have to use the following code, but InputStream is not acceptable by CsvBeanReader method.
beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);
So How can I not only getting the file from resource folder based on the maven structure, but also CsvBeanReader could accept the argument passed in.

Try using InputStreamReader instead of FileReader.
This is possible because the constructor of CsvBeanReader accepts the abstract class Reader:
CsvBeanReader(Reader reader, CsvPreference preferences)
//Constructs a new CsvBeanReader with the supplied Reader and CSV preferences.
You can construct the InputStreamReader using the InputStream you have obtained:
InputStreamReader(InputStream in)
InputStreamReader(InputStream in, Charset cs)
InputStreamReader(InputStream in, CharsetDecoder dec)
InputStreamReader(InputStream in, String charsetName)

You could wrap the java.io.InputStream with a java.io.InputStreamReader (which extends java.io.Reader) and pass it to the CsvBeanReader class.

Related

Is using the File class in Java how you create a file?

I need some serious help with concepts. I have been given background context on the class, specifically this:
I just need to understand the purpose of this class? Can I create a text file (or any other type of file) with its constructors? Is this just for handling files, if so, what does that mean?
Any help whatsoever will be greatly appreciated!
Thank you
You could use the java.io.File to create a file on the file system:
File myFile = new File("myFile.txt");
myFile.createNewFile();
Note that invoking the constructor won't create the file on the file system. To create an empty file, the createNewFile() method has to be invoked.
The File simply represents a abstraction of the file location, not the file itself. It comes with operations on the file identified by the path: exists(), delete(), length(), etc.
What you probably want is to use the classes that allow you to write content to a file:
If you are to write text, you should use the Writer interface.
If you are to write binary content, you should use the OutputStream interface.
The classes FileWriter and FileOutputStream are, respectively, the ones that link the File and Writer/OutputStream concepts together. Those classes create the file on the file-system for you.
FileWriter myFileWriter = null;
File myFile = new File("myFile.txt");
try {
// file is created on the file-system here
myFileWriter = new FileWriter(myFile);
myFileWriter.write("hello");
} finally {
if (myFileWriter != null) {
myFileWriter.close();
}
}
You can create a file using the File.createNewFile method, or, if you are using Java 7 or newer, using the newer Files.createFile method.
The difference between the old File and the new Path classes is that the former mixed a reference to a path to a file on the filsystem and operations you can do on it, and the latter is just representing the path itself but allows you to query it and analyze its structure.

How to access file inside JAR file as a string

I packaged some classes and libraries into a single JAR file. But the current code cannot access the files inside the JAR file as it is.
String scenarioFile = "netlogo/Altruism.nlogo";
// InputStream is = this.getClass().getResourceAsStream(scenarioFile);
simulator = HeadlessWorkspace.newInstance();
simulator.open(scenarioFile);
the .open expects a string but i read that i need to use inputstream format thus its not working. Is there any other workaround?
With the help of Tunaki i was able to get a way about doing it and it worked!
what i did was download commons.io.jar file
import org.apache.commons.io.*;
and then use an inputstream to read the file and then convert it to a string and use openFromSource method that Tunaki suggested of HeadlessWorkspace package to read it.
InputStream is = this.getClass().getResourceAsStream(NetlogoFile);
String scenarioFile = IOUtils.toString(is, "UTF-8");
simulator = HeadlessWorkspace.newInstance();
simulator.openFromSource(scenarioFile);

How to read a file that i created inside my the same package?

This is a chunk of data I'd like to access by a method.
I'm doing the following to read my file:
String fileName = "file.txt"
InputStream inputStream = new FileInputStream(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
My file.txt is in the same package, but I still get FileNotFoundException.
I didn't use a path url to point to the file because I thought since this it going to be an android application, hard-coding the path might not work when deployed... Please correct me if I am wrong. Thanks bunch!
This shows how to do that. https://stackoverflow.com/a/14377185/2801237
Also the 'package' your class is in has nothing to do with the 'path' where the file is being executed from. (two different concepts, 'package' = folder hierarchy of java source code files), 'path' = location on a filesystem of a specific file, your APK is being 'executed' in a particular place, and the location it writes a file is associated with that (I actually don't know where 'offhand' it writes by default, because I always get cache dir, or sd card root, etc.)
You may use:
InputStream inputStream = this.getClass().getResourceAsStream(fileName);

Uploading file to local Eclipse folder

I am trying to get the basics of I/O with Spring.
I am working through the File Upload samples. I want to store the files in a temporary folder in the project for testing.
I have this code:
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name)));
//get directory
stream.write(bytes);
stream.close();
I have created folder "files" within the project files. I want to know how to target the local folder.
I have tried using class File's alternate constructor.
The only way to write files in external(from web container) directory is to use the full direct path to the file. Just use the full file path in following File constructor.
File(String pathname)
Creates a new File instance by converting the given pathname string
into an abstract pathname.

InputStream from jar-File returns always null

i know this question has been asked several times, but i think my problem differs a bit from the others:
String resourcePath = "/Path/To/Resource.jar";
File newFile = new File(resourcePath);
InputStream in1 = this.getClass().getResourceAsStream(resourcePath);
InputStream in2 = this.getClass().getClassLoader().getResourceAsStream(resourcePath);
The File-Object newFile is completely fine (the .jar file has been found and you can get its meta-data like newFile.length() etc)
On the other hand the InputStream always return null.
I know the javadoc says that the getResourceAsStream() is null if there is no resource found with this name, but the File is there! (obviously, because it's in the File-Object)
Anyone know why this happens and how i can fix it so that i can get the .jar File in the InputStream?
The getResourceAsStream() method doesn't load a file from the file system; it loads a resource from the classpath. You can use it to load, for example, a property file that's packaged inside your JAR. You cannot use it to load a file from the file system.
So, if your file resides on the file system, rather than in your JAR file, better use the FileInputStream class.

Categories