Reading .txt files in java - java

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

Related

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

java.io.FileNotFoundException: Joiners.txt (Access Denied)

Here is my problem. The path is true and the error is access denied.
I tried other solution but none of them work for me.
//this is my arraylist which i give value from the txt
ArrayList<Person> PersonArrayList = new ArrayList<Person>();
FileReader inFile = new
FileReader("C:\\Users\\canertasan\\Desktop");
//this is my path but access denied is problem?
BufferedReader inStream = new BufferedReader(inFile);
String InstaNameText;
while ((InstaNameText = inStream.readLine()) != null) {
PersonData.add(new Person(InstaNameText));
inStream.close();
}
The pathname refers to a folder not a file, and you cannot open a folder as a Reader.
The solution depends on what you are trying to do.
If you are trying to read the names of the files in the folder, then use File.list() -> String[] and iterate the array.
If you are trying to read the content of all of the files in the folder, then use File.listFiles() -> File[] and iterate the array. For each file, open, read lines and then close the file.
If you are trying to read the content of a specific file in the Desktop folder, then use the pathname for the file, not the folder.
Desktop isn't a file, it's a folder
FileReader should be given a file name as parameter
String filename = "C:\\Users\\UserName\\Desktop\\Joiners.txt"; //Fullpath txt file
String currentLine; //Current line
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
while((currentLine = br.readLine()) != null){
System.out.println(currentLine);
}
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
catch(IOException ex){
ex.printStackTrace();
}
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
}
catch (IOException ex) {
ex.printStackTrace();
}

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.

Can't find .txt file?

I can't find the .txt file that I want to read from.
Here is the code:
public void read(){
try {
File file = new File("las");
String path = file.getAbsolutePath();
System.out.println(path);
BufferedReader reader = new BufferedReader(new FileReader("/Users/Asus/workspace/testhitodit/las.txt"));
String line = reader.readLine();
while(line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
}catch(FileNotFoundException e) {
System.out.println("File not found");
}catch(IOException e) {
System.out.println("SOmething went wrong");
}
}
This is what gets printed out:
C:\Users\Asus\workspace\testhitodit\las
File not found
And I have a file named las.txt in that folder.
Why doesn't it work?
//include the file extension
File file = new File("las.txt");
String path = file.getAbsolutePath();
System.out.println(path);
//pass the file you created to your file reader
BufferedReader reader = new BufferedReader(new FileReader(file));

Modifying existing file content in Java

I want to replace the second line file content, can somebody help please based on the below file format and listener method.
1324254875443
1313131
Paid
0.0
2nd line is long and want to replace to currentTimeMillis().
/************** Pay Button Listener **************/
public class payListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
ArrayList<String> lines = new ArrayList<String>();
String line = null;
try {
FileReader fr = new FileReader("Ticket/" + ticketIDNumber + ".dat");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("Ticket/" + ticketIDNumber + ".dat");
BufferedWriter bw = new BufferedWriter(fw);
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line.replace(System.currentTimeMillis();
lines.add(line);
bw.write(line);
} //end if
} //end try
catch (Exception e) {
} //end catch
} //end while
}//end method
Although this question is very old I'd like to add that this can be achieved much easier since Java 1.7 with java.nio.file.Files:
List<String> newLines = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8)) {
if (line.contains("1313131")) {
newLines.add(line.replace("1313131", ""+System.currentTimeMillis()));
} else {
newLines.add(line);
}
}
Files.write(Paths.get(fileName), newLines, StandardCharsets.UTF_8);
As proposed in the accepted answer to a similar question:
open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.
Based on your implementation, something similar to:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "try.dat";
String tmpFileName = "tmp_try.dat";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line = line.replace("1313131", ""+System.currentTimeMillis());
bw.write(line+"\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
I could suggest to use Apache Commons IO library. There you'll find the class org.apache.commons.io.FileUtils. You can use it:
File file = new File("... your file...");
List<String> lines = FileUtils.readLines(file);
lines.set(1, ""+System.currentTimeMillis());
FileUtils.writeLines(file, lines);
This code reads entire file contents into a List of Strings and changes the second line's content, then writes the list back to the file.
I'm not sure reading and writing the same file simultaneously is a good idea. I think it would be better to read the file line by line into a String array, replace the second line and then write the String array back into the file.

Categories