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));
Related
I would like to create a temporary txt file for my program. In the code below, "student1.txt" is a txt file that has already created but for "temporarystudent.txt" is is not. I have tried to run with Line 6 (while in Line 7 & 8 in comment) as well as Line 7 & 8 (while Line 6 in comment) but neither of them are able to create "temporarystudent.txt". When I run the program, it didn't show any error neither in VS Code Terminal nor in the Program Output. It just won't create the "temporarystudent.txt". May I know what's wrong here?
try
{
//Locate the file.
File file = new File("student1.txt");
//Create a temporary file
//File temp = File.createTempFile("temporarystudent", ".txt", file.getParentFile());
File temp = new File("temporarystudent.txt");
temp.createNewFile();
//Determine the charset.
String charset = "UTF-8";
//Open the file for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
//Open the temp file for writing.
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
//Read the file line by line.
for (String line; (line = reader.readLine()) != null;) {
line = line.replace("null\n", "");
writer.println(line);
}
//Close the reader and writer (preferably in the finally block).
reader.close();
writer.close();
//Delete the file.
file.delete();
//Rename the temp file.
temp.renameTo(file);
}
catch (IOException e)
{
System.out.println("An error occurred.");
e.printStackTrace();
}
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();
}
While creating a method to my class, I got an unexpected problem. I've tried solutions from other theards, but they just don't work for me. My method should simply find the line specified, copy the file skipping unnecessary line, delete the original file and rename temporary file to the name of original file. It succesfuly creates new file as expected, but then fails to delete previous one as it fails to rename temporary file to original. I can't figure out, why?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
Try this code:
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
BufferedReader reader = new BufferedReader(new FileReader(theFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
theFile.delete();
temp.renameTo(file_name + ".txt");
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
I could suggest a couple of reasons why the delete and/or rename might fail, but there is a better way to solve your problem than guessing1.
If you use Path and the Files.delete(Path) and Files.move(Path, Path, CopyOption...) methods, they will throw exceptions if the operations fail. The exception name and message should give you clues as to what is actually going wrong.
The javadoc is here and here.
1 - Here are a couple of guesses: 1) the file has been opened elsewhere, and it is locked as a result. 2) You don't have access to delete the file.
Im having a problem in checking if a file exists in Java. However the IF block seems to work , but the ELSE seems dont. see, when a file exist, it will prompt a box that says, 'File found.' which happens in my program whenever a file do exist, the problem is errors flood in my console when a file dont exist. Can somebody tell me what's the easier and shorter way of coding my problem? thanks ! here's my code
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
File f = new File(textField.getText());
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
{
JOptionPane.showMessageDialog(null, textField.getText()+" found" );
while ((sCurrentLine = br.readLine()) != null) {
textArea.append(sCurrentLine);
textArea.append(System.lineSeparator());
}
}
else
{
JOptionPane.showMessageDialog(null, textField.getText()+" not found" );
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
The problem is with this line:
br = new BufferedReader(new FileReader(path+f));
You're appending a File to a String, which doesn't make sense. You should append a String to a String, in this case textField.getText()) appended to path.
This line will throw an exception if the file doesn't exist as per the documentation of FileReader:
Throws:
FileNotFoundException - if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
This causes your program to reach the catch clause and print an exception stack trace. You should only call this line when f.exists() returns true:
if (f.exists())
{
br = new BufferedReader(new FileReader(path + textField.getText()));
...
}
Look at these lines of your code:
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
You are trying to open the file before checking whether it exists. So if the attempt to open it fails with a FileNotFoundException, the test is never reached.
String path = "C:\\Path\\To\File\\Directory\\";
String fileName = "NameOfFile.ext";
File f = new File(path, fileName);
if(f.exists()) {
//<code for file existing>
} else {
//<code for file not existing>
}
You have to instantiate the BufferedReader after checking the existence of the file.
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
File f = new File(path + textField.getText());
...
if (f.exists())
{
br = new BufferedReader(new FileReader(f.getAbsolutePath())); // or br = new BufferedReader(f);
...
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");