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.
Related
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();
How do I convert the FileWriter to OutputStreamWriter? This is the directory that I stored the .java files. src/RX/example.java where RX is the package name. I inserted all the images and text files inside the same directory. Here is my working code with FileWriter.
try {
StringReader stringReader = new StringReader("Save this Message");
BufferedReader bufferedReader = new BufferedReader(stringReader);
FileWriter fileWriter = new FileWriter("src/RX/rxUser.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(String line = bufferedReader.readLine(); line != null; line =bufferedReader.readLine()) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I actually can go on with this code but in order to work with .jar I have to use the .txt file as a resource. Can someone please alter my code. I am using Netbeans. Thank you.
I have a file with cyrillics and non-cyrillics characters. However, when I read the file the cyrillics characters are not retrived and non-cyrillics characters are retrived. Here is the code I am using
private static String dirToPRocess = "D:\\stopwords_freq_v2.txt";
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(
dirToPRocess), "UTF-8"));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Are you using eclipse?
You can try the following to get it to work:
save your java file with the character encoding utf-8.
If you want to print cyrillics to the console, I think there might be a setting in eclipse's properties somewhere that does that but not 100% certain- it should print cyrillics by default in my experience.
Your java code looks OK btw.
I am trying to open a .txt file saved within a JAR and display its contents in a JTextArea. Below is the code I am trying to use;
URL urlToDictionary = this.getClass().getResource("eula/" + "eula.txt");
try {
InputStream stream = urlToDictionary.openStream();
gettysburgTextStrBlder = stream;
System.out.println(stream);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I know I am in the correct file location as I have changed the .getResource path around and seen null point exceptions, I have none with the current file path.
The System.out prints the following at runtime:
java.io.BufferedInputStream#3af42ad0
I have also tried;
gettysburgTextStrBlder = String.valueOf(stream);
But the result I get is the same.
I think I am nearly there, but am unsure how to get the actual content of the .txt file and not just the Buffered stream.
Thanks.
Andy
You have to read the content from the inputstream and display in the text area using BufferedReader
URL urlToDictionary = this.getClass().getResource("eula/" + "eula.txt");
try {
InputStream stream = urlToDictionary.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = null;
StringBuffer lineContent = new StringBuffer();
while((line = br.readLine()) != null){
lineContent.append(line).append("\n");
}
br.close().
System.out.println(lineContent.toString());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
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("Smokey")){
line = line.replace("Smokey;","AAAAAA;");
bw.write(line+"\n");
} else {
bw.write(line+"\n");
}
}
}
catch (Exception e) {
return;
} finally {
try {
if(br != null){
br.close();
messagejLabel.setText("Error");
}
} 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);
When running the code above I end up with an empty file "tmpfiles.txt" and the file "files.txt is being deleted. can anyone help? I don't want to use a string to read the file. I would prefer to do it his way.
A quick test confirmed that not closing the writer as I wrote in my comment above actually produces the behavior you describe.
Just add
if (bw != null) {
bw.close();
}
to your finally block, and your program works.
I found some issue in your code.
First, this line seems not correct:
if (line.contains("Smokey")){
line = line.replace("Smokey;","AAAAAA;");
bw.write(line+"\n");
it should be:
if (line.contains("Smokey;")){
line = line.replace("Smokey;","AAAAAA;");
bw.write(line+"\r\n");
And, you should flush and close the bw after finish it.
if (bw != null){
bw.flush();
bw.close();
}
Correct me if I'm wrong.
The file is never written to because the writer was never "flushed". When closing the writer all the data in the buffer is automatically written to the file. Get used to standards with streams where you close them in a try-catch block.