I am trying to read from a file, but i just don't get it how can i do so while using a try catch block ... How can i make it throw exception if something bad happens, but if it's ok to execute this line : br.readLine() ? It just say that br is not declared. What if i need to use "br" and "bw" somewhere different(like a different method) ? Do i have to declare them there too ?
try {
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
br.readLine();
br is declared in the scope of the try and therefore is gone after the catch. You want to do this:
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
e.printStackTrace();
}
br.readLine();
Note you risk the null pointer after the catch so another option would be to write the br.readLine() into the try, like this:
try {
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
You have declared BufferedReader and BufferredWriter within the try block and calling br.readline() outside the try and catch and hence it doesn't know where the br has been declared. I have the same answer as above.
try {
BufferedReader br = new BufferedReader(new FileReader(new File ("path_to_your_file_to read")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("path_to_your_file_to_write")));
br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader and BufferedWriter should be define outside from try and catch block than only we can access them outside
Try this code, it should work
BufferedReader br = null;
BufferedWriter bw =null;
try {
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
br.readLine();
Related
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 6 years ago.
private void AddAccount(String usernamenew, String passwordnew) {
final String FileName = "F:/TextFiles/loginaccs.txt";
File file = new File(FileName);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(usernamenew);
bw.newLine();
bw.write(passwordnew);
bw.newLine();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, I tried to write two extra lines to a text file, which is a new username and a new password.
After deleting some of the lines, the program deletes everything in the text file and write two lines, which is not what I wanted.
Am I doing something wrong? Thanks in Advance.
After you write to the BufferedWriter, for the file, you then close it, which is fine.
However, you then create another FileOutputStream. In addition, you should not have a reader and writer of the same file at the same time. All you need to do is create the BufferedWriter, write the file and close it.
private void AddAccount(String usernamenew, String passwordnew) {
final String FileName = "F:/TextFiles/loginaccs.txt";
File file = new File(FileName);
try {
// BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(usernamenew);
bw.newLine();
bw.write(passwordnew);
bw.newLine();
bw.close();
// FileOutputStream fos = new FileOutputStream(file);
// fos.close();
// br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I am trying to rewrite in a file, alongside with the other text in it(not overwrite). But i don't know how can i do it using the exception as my buffered reader lose his initialization.
BufferedReader br;
try {
br = new BufferedReader(new FileReader("file.txt"));
String line ;
while((line = br.readLine()) != null){
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedWriter bw;
try {
File file = new File("file.txt");
bw = new BufferedWriter(new FileWriter("file.txt"));
if(br.readLine() != null) //ERROR Local variable may have not been initialized
bw.newLine();
bw.write("Hello");
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
FileWriter has the ability to set the append flag new FileWriter(file, append)
or if you want to use your version
Initialize the variable with null
BufferedReader br = null;
try with resource may be useful here as well, because it closes everything for you automatically.
Simple. Initialize the variable to null.
Say first line as,
BufferedReader br = null;
...
try {
File file = new File("file.txt");
bw = new BufferedWriter(new FileWriter("file.txt",true));
if(br.readLine() != null) //ERROR Local variable may have not been initialized
...
Try that on for size. That "true" after file.txt means it will append to what file you've found.
Here's a link to the documentation. Take note of the last constructor for FileWriter.
BufferedReader br = null;
To fix your current error changing your first line to this would be how you do it. That reader however is not needed whatsoever.
I have a problem with writing data to my .txt file. It doesn't write all the data to my .txt file. I have tried it to put everything in a array, but also that doesn't works.
My code:
BufferedWriter writer = null;
try {
String line;
Process p = Runtime.getRuntime().exec("ps -A -o pid");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
writer = new BufferedWriter(new FileWriter(" the path .."));
writer.write(line);
System.out.println(line);
}
writer.close();
input.close();
} catch (Exception err) {
err.printStackTrace();
System.out.println("Sorry!");
}
It writes only the last line of the console.
By re-creating the object without closing it during every iteration of the loop, you are discarding what you have written so far (You have to use writer.close() to save what you have written using the object).
You will need to declare writer before the loop, so change it to the following
BufferedWriter writer = null;
try {
String line;
Process p = Runtime.getRuntime().exec("ps -A -o pid");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
writer = new BufferedWriter(new FileWriter(" the path .."));
while ((line = input.readLine()) != null) {
writer.write(line);
System.out.println(line);
}
writer.close();
input.close();
} catch (Exception err) {
err.printStackTrace();
System.out.println("Sorry!");
}
Can I just ask, why were you re-declaring the writer object every iteration?
I am opening a new file and trying to write to it inside a sub process in java. I used the process builder to start the sub process. The file is being created but whatever content I want to write to the file is not getting written. Is there a way to solve this? I can redirect stdin, stdout and stderr of sub process but how to redirect the file I/O. I want to do it on java version 1.7
process is started:
ArrayList<String> params = new ArrayList<String>();
for (int i = 0; i < cmdarray.length; i++) {
params.add(cmdarray[i]);
}
try {
//java.lang.Process process = Runtime.getRuntime().exec(cmdarray);
ProcessBuilder builder = new ProcessBuilder(params);
final java.lang.Process process = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
file is created inside the sub process:
BufferedWriter br;
try {
br = new BufferedWriter(new FileWriter(new File("text.txt")));
br.write("This should be present in the file.");
}
catch (IOException e) {
e.printStackTrace();
}
You forget to close the BufferedWriter br, this is why the String is not getting written in the file.
Try this, may help :
BufferedWriter br;
try {
br = new BufferedWriter(new FileWriter(new File("text.txt")));
br.write("This should be present in the file.");
br.close();
} catch (IOException e) {
e.printStackTrace();
}
My code is reading an HTML page from the web and I want to write good code, so I would like to close the resources using try-with-resources or finally block.
With the following code it seems impossible to use either of them to close "in".
try {
URL url = new URL("myurl");
BufferedReader in = new BufferedReader(
new InputStreamReader(
url.openStream()));
String line = "";
while((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (IOException e) {
throw new RuntimeException(e);
}
Would you be able to write the same code using try-with-resources or finally?
I don't see any particular difficulty with the following:
try (BufferedReader in = new BufferedReader(new InputStreamReader(
new URL("myurl").openStream()))) {
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
Is it not what you're looking for?