I'm new to Java and I'm trying to use this class to return the content of "test.csv".This only works when I use the path of local files.
public class CSVtoArray2 {
public static final String filename = "C:\\eclipse\\workspace\\project\\src\\main\\webapp\\resources\\csv\\test.csv";
public String testMethod() throws IOException {
BufferedReader wr = null;
try {
wr = new BufferedReader(new FileReader(new File(filename)));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = wr.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
wr.close();
return stringBuffer.toString();
} finally {
wr.close();
}
}
}
When I change
"C:\eclipse\workspace\project\src\main\webapp\resources\csv\test
.csv"
to "/resources/csv/test.csv",
this class gets a null return.
Anyone here who can help?
Thanks!
UPDATE:
Solution:
Copying my CSV file to project resources folder:
ClassLoader classLoader = getClass().getClassLoader();
File filename = new File(classLoader.getResource("csv/test.csv").getFile());
org.apache.commons.io.IOUtils.toString(CSVtoArray2.class.getResourceAsStream("/csv/test.csv"), Charset.forName("UTF-8")))
It is tricky, what is root path for the resource. In Eclipse you can mark some folder (e.g. webapp/recource) as resource folder. And When you build jar file, resource folder content will be in the root. So if you start your resource path from /, it means root of jar (i.e. root of resource folder).
I do not use relative paths, so you could look at open resource with relative path in java to get more info about it.
Related
This question already has answers here:
How do I load a file from resource folder?
(21 answers)
Closed 2 years ago.
I found this file exist in the url showed, but still get NoSuchFileException.
Had try many way but the path return always same, but cant read the file. How it will be? It there but not there? why plz?
public void readFile() throws IOException {
String fileName = "domain.txt";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
//File is found
System.out.println("File Found : " + file.exists());
//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
}
When you use ClassLoader you must use absolute path
public void readFile() throws IOException {
// Must use absolute path here, so start with a slash
String fileName = "/domain.txt";
// Use InputStream instead of File
InputStream input = ClassLoader.getSystemResourceAsStream(filename);
BufferedReader bf = new BufferedReader(new InputStreamReader(input));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bf.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
System.out.println(content);
}
In my program I made a saving and loading system for text files. The Save function works perfectly as intended but the Load gives a NullPointerException.
Here's the load function
String path = "C:\\Levels\\File.txt";
LevelHandler.loadLevel(path);
Here's the loadLevel function
public static void loadLevel(String file){
String level = LevelLoader.loadFileAsString(file);
//other, unimportant, code
}
And here's the loadFileAsString function
public static String loadFileAsString(String file){
StringBuilder builder = new StringBuilder();
try {
InputStream in = LevelLoader.class.getResourceAsStream(file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = bufferedReader.readLine()) != null){
builder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
It's failing because it's looking for the file in the class folder regardless of what directory I pass in. How can I get the location of the .jar regardless of where the user places it on their computer?
you can get the .jar related location using ./
./ provides related path of your jar
The fix I came up with was to remove the InputStreamreader
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
This will be able to read files from any specified location on the computer, but still not from inside the jar. However it works perfectly fine with pretty much any other specified location.
In my function I want to read a text file. If file does not exists it will be created. I want to use relative path so if i have .jar, file will be created in the exact same dir. I have tried this. This is my function and variable fName is set to test.txt
private static String readFile(String fName) {
String noDiacText;
StringBuilder sb = new StringBuilder();
try {
File f = new File(fName, "UTF8");
if(!f.exists()){
f.getParentFile().mkdirs();
f.createNewFile();
}
FileReader reader = new FileReader(fName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fName), "UTF8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
I am getting an error at f.createNewFile(); it says
java.io.IOException: System cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at main.zadanie3.readFile(zadanie3.java:92)
The problem is that
File f = new File(fName, "UTF8");
Doesn't set the file encoding to UTF8. Instead, the second argument is the child path, which has nothing to do with encoding; the first is the parent path.
So what you wanted is actually:
File f = new File("C:\\Parent", "testfile.txt");
or just:
File f = new File(fullFilePathName);
Without the second argument
Use mkdirs() --plural-- to create all missing parts of the path.
File f = new File("/many/parts/path");
f.mkdirs();
Note that 'mkdir()' --singular-- only creates the list part of the path, if possible.
I used Class.getResource (String) to retrieve the url of a file, and it works very well, but when I try to 'insatncié a FileReader with the url returned, an exception:java.io.FileNotFoundException is triggered
URL bpmnResourceUrl = ConvertXmlToJson.class.getClassLoader().getResource("file.txt");
Reader reader = new FileReader(bpmnResourceUrl.toString());
A Resource in Java is not a File. If the Resource is inside a JAR, for example, you can't access it like a File. You have to explode the JAR first. You may try:
Class.getResourceAsStream()
to read the content. Here is a short example:
public class Example {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(Example.class.getResourceAsStream("/META-INF/MANIFEST.MF")));
String line;
do {
line = br.readLine();
if (line != null) System.out.println(line);
} while (line != null);
}
}
Don't open it as a file, use it as InputStream, in your case, if you want a Reader to get the data then you can use:
InputStream is = ConvertXmlToJson.class.getClassLoader().getResourceAsStream("file.txt");
Reader reader = new InputStreamReader(is);
When you load a resource from Classpath, such resource can be located inside a jar file, so It's not accesible like a regular file in filesystem, but you can open a Stream to read it, as the code shows.
I have an eclipse project and in one folder there is a text file "conf.txt". I can read and write the file when I use the path on my Computer. But I have to write my own folders there as well, not only the workspace folders.
So know I want to commit the program for others, but then the path I put in the program won't work, because the program is running on a different computer.
What I need is to be able to use the file with only the path in my workspace.
If I just put in the path, which is in the workspace it won't work.
This is how my class File looks like.
public class FileUtil {
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = "";
while ((line = reader.readLine()) != null) {
returnValue += line + "\n";
}
reader.close();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
return returnValue;
}
public void writeTextFile(String fileName, String s) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
try {
output.write(s);
}
finally {
output.close();
}
}
}
I hope someone knows what to do.
Thanks!
I am not sure but I attached the screen shot with little bit explanation. Let me know if you have any question.
Your project is root folder here and images as resources folder from where you can access the file using relative path.
// looks for file in root --> file.txt
scan = new Scanner((new File("file.txt")));
// looks for file in given relative path i.e. root--> images--> file.txt
scan = new Scanner((new File("images/file.txt")));
If you want your configuration file to be accessed through a relative path, you shouldn't need to add anything to the front of it. Assuming you're using a bufferedReader, or something of the sort it would look as simple as: br = new BufferedReader(new FileReader("config.txt"));
This will cause a search of the runtime directory, making it so you don't have to fully qualify the path to your file. That being said you have to ensure your config.txt is within the same directory as your executable.