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();
}
Related
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);
Given my project structure below,
My Project structure
How do I access findLoginDetails.txt?
Currently, I have
public static String getQueryFromExternalFile(final String path) {
String path1 = "src/main/resources/sql/C0001/findLoginDetails.txt";
String query = "";
try {
BufferedReader br = new BufferedReader(new FileReader(path1));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
query = sb.toString();
br.close();
} catch (Throwable e) {
query = "";
e.printStackTrace();
}
return query;
}
But it's not working. Any idea why it's not working?
You are better off reading it from the classpath than the project root folder. I assume the resources folder is on your build path. This will give you the portability you want.
Use
BufferedReader r = new BufferedReader(
new InputStreamReader(MyClass.class.getClassLoader().getResourceAsStream(
"sql/C0001/findLoginDetails")));
Where 'MyClass' is the name of your class.
See How to really read text file from classpath in Java for a better understanding.
Have you tried putting the absolute path ?
If in Windows try putting "D:\path\to\file"
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 have a program that saves on a file. The current code is set for the file to save on a specific path, but when I run the program from a different computer the program doesn't work and I need to change the path everytime.
public CreateCustomer() {
initComponents();
ArrayList<String> ConsIDList = new ArrayList<String>();
String csvFileToRead = "E:\\ryan_assignment_sit2\\ConsID\\consID.csv"; // Reads the CSV File.
BufferedReader br = null; // Creates a buffer reader.
String line = "";
String splitBy = ","; // Reader Delimiter
try {
br = new BufferedReader(new FileReader(csvFileToRead)); // Buffer Reader with file name to read.
Scanner reader = new Scanner(System.in);
while ((line = br.readLine()) != null) { //While there is a line to read.
reader = new Scanner(line);
reader.useDelimiter(splitBy);
while (reader.hasNext()) { // While there is a next value (token).
ConsIDList.add(reader.next());
}
}
} catch (FileNotFoundException exception) { // Exception Handler if the File is not Found.
exception.printStackTrace();
} catch (IOException exception) { // Input/Output exception
exception.printStackTrace();
} finally {
if (br != null) {
try {
br.close(); // Close the Scanner.
} catch (IOException exception) {
exception.printStackTrace();
}
}
I placed the file in the a subfolder in the program with the name ConsID and I tried changing the path file to
String csvFileToRead = "..\\ConsID\\consID.csv";
But the file can't be read from the program.
String csvFileToRead = "E:\ryan_assignment_sit2\ConsID\consID.csv";
The above path will only be applicable to windows. If you execute the program in linux environment you will get an Filenotfoundexception. Eventhough you change the file, again you are hardcoding the file path.
Better you can get it as runtime parameters so that the program will be executed irrespective of OS.
If you are running you program from command line then you can place the csv file in your classpath (root folder where the class files are generated) and refer to it as below:
BufferedReader br = new BufferedReader(ClassLoader.getResourceAsStream("consID.csv"));
Reading a file in Java. I get the "FileNotFound" exception.
Exception:
java.io.FileNotFoundException: something.txt (The file was not found)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at rmihello.ReadStringFromFileLineByLine.main(ReadStringFromFileLineByLine.java:13)
Even though my file is in my bin right next to my sourcecode:
I have also tried giving it the entire path to my file, e.g.
path = "C:/Users/Alexander/Desktop/java/something.txt"
or
path = "cd 'C:/Users/Alexander/Desktop/java/something.txt'"
All of it fails
Here's my code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileLineByLine {
public static void main(String[] args) {
try {
String path = "something.txt";
File file = new File(path);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
A relative path adds to uncertainty where a file-not-found stems from.
As you tried alternatives, handle the error:
File file = new File("C:/.../something.txt");
try {
...
} catch (FileNotFoundException e) {
File full = file.getAbsoluteFile();
File dir = file.getParentFile();
while (dir != null && !dir.exists()) {
dir = dir.getParentFile();
}
System.out.printf("File %s does not exist under %s%n",
full.getPath(),
dir == null ? "/" : dir.getPath());
} catch (IOException e2) {
}
Tips:
StringBuilder is faster, successor of StringBuffer.
New style (since Java 7):
Path path = Paths.get("C:/...");
byte[] content = Files.readAllBytes(path);
String contentText = new String(content); // Default encoding
As mentioned in comments, your code should start like this:
Path file = ; //Specify the path to your file
Take a look at Reading, Writing, and Creating Files in Java for more information
Edit:
Just edit your code like this it works fine for me:
public static void main(String[] args){
String path = "C://Something.txt"; // I put the file under the C: path in my example
try {
File file = new File(path);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
Then just change the path to fit yours.
if you insert your text files into a folder named text_files for example, then you can access it using
File f = new File("text_files/something.txt");