I have an app, that needs to read files line by line. I'm using the following code and it's ok.
public ArrayList <String[]> LoadServersFile(String filename){
BufferedReader br=null;
ArrayList <String> result = new ArrayList();
try {
String sCurrentLine;
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("/"+filename));
br = new BufferedReader(new FileReader(filename));
while ((sCurrentLine = br.readLine()) != null) {
result.add(sCurrentLine);
}
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(FilesIO.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FilesIO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
But after compiling project and launching it, br.readLine() is always null. Setting "/file.txt" and putting this file to C:/ disk fixes the bug, but i need this file to be in folder with my .jar file
You can get your file using the getResourceAsStream method:
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("/file.txt"));
BufferedReader br = new BufferedReader(reader);
Related
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();
}
What i'm trying to do, is to replace a symbol in a file text which contains over 4000 lines but using the below code, after the program ends, it only remain 500 lines. Why is this file truncated? How to solve this?
This is my code:
ArrayList<String> arrayList = new ArrayList<>();
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {System.err.println(e);}
}
} catch (Exception e) {e.printStackTrace();}
Thanks in advance!
new BufferedWriter(new FileWriter(file)) clear file.
You should open it only once. Also you reading and writing to the same file. You should use different files.
Like this
try (FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
bw.write(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
You are writing to the same file while you are reading it. This won't work. Once you start writing, the file becomes empty (plus whatever you've written), so subsequent reads will report end-of-file. Your ~500 lines will be buffered input from the first read.
One solution is to do all the reading first, before opening the file again for writing:
Array<String> arrayList = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
while ((String line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {
System.err.println(e);
}
Here, first the program slurps the file into a List<String>, fixing the lines as it goes. Then it writes all the lines back out to the file.
There are circumstances in which this model is appropriate. For example, you might be building a non-linear data structure from the file content. Or you might need to see the last line before you can modify earlier lines (and be unable to re-open the data source from the start).
However I'd suggest a method that's more thrifty with memory. You don't need to keep all those lines in memory. You can read one line, fix it up, then forget about it. But to do this, you'll need to write to a second file.
String filein = "inputfile";
String fileout = filein + ".tmp";
try(
BufferedReader reader = new BufferedReader(new FileReader(filein));
Writer writer = new BufferedWriter(FileWriter(fileout))
) {
while ((String line = bufferedReader.readLine()) != null) {
writer.write(line.replace("þ", "t");
}
}
Files.move(Paths.get(fileout)),
Paths.get(filein),
CopyOption.REPLACE_EXISTING);
I have left out the necessary exception catching -- add back in as required.
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);
...
I'm reading a txt with BuffererReader and I wonder how to give the path to my txt in BufferedReader's argument.
BufferedReader input = new Bufferedreader(
new FileReader(D:VI.félév\Prog gyak\Project\proba.txt));
This doesn't seem to work.
Your problem is:
new Filereader( .. )
should be
new FileReader( .. )
And the path has to look like:
new FileReader("D:\\directory\\proba.txt");
You need an additional \ as escape character
Full Working Example with try..catch if problem any occur.
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("D:\\directory\\proba.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
I have method which writes some data to file. I use PrintWriter, BufferedWriter and FileWriter as shown below
public void writeToFile(String FileName){
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
for(Cars car : list){
pw.println(car.getType());
pw.println(car.getMaxSpeed());
pw.println(car.getOwner());
pw.println();
pw.flush();
}
pw.close();
}
catch(IOException ex){
System.err.println(ex);
}
}
Now how can I read this data from file? I tried to use InputStreamReader, BufferedReader and FileInputStream, but my NetBeans shows me an error message
public void readFromFile() throws IOException {
InputStreamReader fr = null;
try {
fr = new InputStreamReader(new BufferedReader(new FileInputStream(new FileReader("c:\\cars.txt"))));
System.out.println(fr.read());
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
fr.close();
}
}
What is wrong with this method?
BufferedReader in = new BufferedReader(new FileReader("file.in"));
BufferedWriter out = new BufferedWriter(new FileWriter("file.out"));
String line = in.readLine(); // <-- read whole line
StringTokenizer tk = new StringTokenizer(line);
int a = Integer.parseInt(tk.nextToken()); // <-- read single word on line and parse to int
out.write(""+a);
out.flush();
There are several problems in your code :
1) An InputStreamReader takes an InputStream as an argument not a Reader. See http://docs.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html.
2) The FileInputStream does not accept a Reader as argument as well (it takes a File, a FileDescriptor, or a String). See : http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html
3) A BufferedReader reads the File line by line normally. The read() method only reads a single character.
A possible solution could be :
fr = new BufferedReader(new InputStreamReader(new FileInputStream(new File("c:\\cars.txt"))));
String line = "";
while((line = fr.readLine()) != null) {
System.out.println(line);
}
Btw : It would be easier for others to help you, if you provide the exact error-message or even better the StackTrace.
Simple error: Cannot resolve constructor 'FileInputStream(java.io.FileReader)', required constructor not exist in API.
Your original code was:
new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
so for reading, you need
new PrintReader(new BufferedReader(new FileReader(FileName)));
but PrintReader is not needed (not exist), so all you need is:
new BufferedReader(new FileReader(FileName))
PrinterWriter prints formatted representations of objects to a text-output stream, but when reading text is always formatted, so PrinterReader not exist.
You are writing line by line, so also read line by line :) Example:
public void readFromFile() throws IOException {
BufferedReader bufferedReader = null;
try {
String sCurrentLine;
bufferedReader = new BufferedReader(new FileReader("c:\\cars.txt"));
while ((sCurrentLine = bufferedReader.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
bufferedReader.close();
}
}
or better (JDK7)
void readFromFile() throws IOException {
Path path = Paths.get("c:\\cars.txt");
try (BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset())){
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}