read file from resource Java [duplicate] - java

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);
}

Related

merge file and delete the old file

I have been trying to merge two files into new file and below code does it job. But after the merge i want to delete the old files. The code I am using to delete files just delete 1 file (file2) not the both of them.
public static void Filemerger() throws IOException
{
String resultPath = System.getProperty("java.io.tmpdir");
File result = new File(resultPath+"//NewFolder", "//file3.txt");
// PrintWriter object for file3.txt
PrintWriter pw = new PrintWriter(result);
// BufferedReader object for file1.txt
BufferedReader br = new BufferedReader(new FileReader(resultPath+"file1.txt"));
String line = br.readLine();
// loop to copy each line of
// file1.txt to file3.txt
while (line != null)
{
pw.println(line);
line = br.readLine();
}
pw.flush();
br = new BufferedReader(new FileReader(resultPath+"file2.txt"));
line = br.readLine();
// loop to copy each line of
// file2.txt to file3.txt
while(line != null)
{
pw.println(line);
line = br.readLine();
}
pw.flush();
// closing resources
br.close();
pw.close();
File dir = new File(resultPath);
FileFilter fileFilter1 = new WildcardFileFilter(new String[] {"file1.txt", "file2.txt"}, IOCase.SENSITIVE);
File[] fileList1 = dir.listFiles(fileFilter1);
for (int i = 0; i < fileList1.length; i++) {
if (fileList1[i].isFile()) {
File file1 = fileList1[i].getAbsoluteFile();
file1.delete();
}
}
}
I also try this code to delete the file1 as above code delete the file2:
Path fileToDeletePath = Paths.get(resultPath+"file1.txt");
Files.delete(fileToDeletePath);
but it throws an exception that Exception in thread "main" java.nio.file.FileSystemException: C:\Users\haya\AppData\Local\Temp\file1: The process cannot access the file because it is being used by another process.
Closing the streams as suggested in the comments will fix. However you are writing a lot of code which is hard to debug / fix later. Instead simplify to NIO calls and add try with resources handling to auto-close everything on the way:
String tmp = System.getProperty("java.io.tmpdir");
Path result = Path.of(tmp, "NewFolder", "file3.txt");
Path file1 = Path.of(tmp,"file1.txt");
Path file2 = Path.of(tmp,"file2.txt");
try(OutputStream output = Files.newOutputStream(result)) {
try(InputStream input = Files.newInputStream(file1)) {
input.transferTo(output);
}
try(InputStream input = Files.newInputStream(file2)) {
input.transferTo(output);
}
}
Files.deleteIfExists(file1);
Files.deleteIfExists(file2);

The system cannot find the file specified - Netbeans Maven Project

I need to read two .json files, I have added them to my src folder of NetBeans folder but it is not finding the file.
I have tried using path in following ways,
"/krf_input_cases.json",
"krf_input_cases.json",
"/com.mycompany.reasoner/krf_input_cases.json"
after checking here on StackOverflow but it is not working. The still same error that file cannot be found!
Here you can see where is my file is in the document tree:
This is where I have specified my file paths
//file paths
private static final String KRF_INPUT_CASES = "krf_input_cases.json";
private static final String KRF_KNOWLEDGE_BASE = "krf_knowledge_base.json";
Here is the function reading the file which is throwing an exception!
public static String loadData(String filePath) throws Exception {
System.out.println("line");
BufferedReader br = null;
try{br = new BufferedReader(new FileReader(
new File(filePath)));} catch (Exception e){
System.out.println(e.getMessage());
}
System.out.println("line1");
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line.trim());
}
br.close();
return sb.toString();
}

bufferedReader only read local csv file

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.

How to find the file mime-type / content-type using the file binary content?

I have file content which is currently as byte[] and I want to know it's mime-type / content-type header.
The issue is that, I saw many examples over the web to find it but only when the file is actually exists.
How can I get this info by only this byte[].
Most of the codes which I tested are like:
File f = new File("gumby.gif");
System.out.println("Mime Type: " + new MimetypesFileTypeMap().getContentType(f));
EDIT 1:
This code gave me a wrong result which is: application/octet-stream
Is there a way to get this info without creating a file ?
EDIT 2:
I tried this code:
public static void main(String[] args) throws Exception{
Tika tika = new Tika();
byte[] content = readFile().getBytes();
System.out.println(tika.detect(content));
}
private static String readFile() throws Exception{
BufferedReader br = new BufferedReader(new FileReader("c:\\pic.jpg"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
return everything;
} finally {
br.close();
}
}
And it's always returns application/octet-stream, is it because i'm using byte[] as parameter?

Java create file if does not exist

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.

Categories