This is my first attempt at file writing to save data in a java program, and i found this solution here on SO, but i am getting an error in my finally statement when i try to close the PrintWriter, saying "out cannot be resolved".
Much thanks.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class MedConcept {
public static void main(String[] args) {
ConsoleReader console = new ConsoleReader(System.in);
try {
PrintWriter out = new PrintWriter("med.txt");
System.out.println("Name of the medication:");
String medName = console.readLine();
System.out.println("The Dosage of the medication:");
Double medDose = console.readDouble();
System.out.println("Time of day to take");
String dayTime = console.readLine();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
out.close();
}
}
}
The variable out is declared inside the try block which is not visible in the finally block. Move the declaration outside and add a check on whether it is null when closing it.
PrintWriter out = null;
try {
out = new PrintWriter("med.txt");
System.out.println("Name of the medication:");
String medName = console.readLine();
System.out.println("The Dosage of the medication:");
Double medDose = console.readDouble();
System.out.println("Time of day to take");
String dayTime = console.readLine();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(out != null) {
out.close();
}
}
If you're using Java 7, you can avoid manually closing the PrintWriter with a try-with-resources statement.
try (PrintWriter out = new PrintWriter("med.txt")) {
...
} catch() {
...
}
Related
Can somebody tell me what am I doing wrong in the below java code ? It doesn't compile and gives me compilation error.
import java.io.*;
public class ShowFile {
public static void main(String[] args) {
int i;
FileInputStream Fin;
try {
Fin = new FileInputStream("C:\\Users\\cbr\\Desktop\\test.txt");
} catch (FileNotFoundException exp) {
System.out.println("exception caught" + exp);
}
try {
do {
i = Fin.read();
System.out.print((char) i);
} while (i != -1);
} catch (IOException exp) {
System.out.println("Exception caught" + exp);
}
finally {
try {
Fin.close();
} catch (IOException exp) {
System.out.println("Exception caught" + exp);
}
}
}
}
while the below code compiles. You can see both initialization are within try block.
import java.io.*;
class ShowFile2 {
public static void main(String args[]) {
int i;
FileInputStream fin;
// First make sure that a file has been specified.
try {
fin = new FileInputStream("C:\\Users\\cbr\\Desktop\\test.txt");
} catch (FileNotFoundException exc) {
System.out.println("File Not Found");
return;
}
try {
// read bytes until EOF is encountered
do {
i = fin.read();
if (i != -1) {
System.out.print((char) i);
}
} while (i != -1);
} catch (IOException exc) {
System.out.println("Error reading file.");
}
try {
fin.close();
} catch (IOException exc) {
System.out.println("Error closing file.");
}
}
}
The problem is, that if new FileInputStream("C:\\Users\\cbr\\Desktop\\test.txt"); throws an exception, your variable will not be initialized in the second part of your method. This is not allowed. Object members will be initialized to null when the object is created, but this is not the case for local variables: they must be initialized explicitly.
A quick fix (but read on for a better fix) would be to initialize your variable (to null) when you are defining it:
FileInputStream fin = null;
This will solve your compilation error, however, you will get NullPointerExceptions when an exception is thrown in the first catch block.
A better solution is to put your error handling logic in the same place: if creating the FileInputStream fails, you don't want to read bytes from it anyway. So you can use a single try-catch block:
try {
fin = new FileInputStream("C:\\Users\\cbr\\Desktop\\test.txt");
// Read bytes from fin.
...
} catch (IOException e) {
// handle exception
...
}
Final advice: to make sure that your input stream is closed in all circumstances, you can use a try-with-resources block:
try (fin = new FileInputStream("C:\\Users\\cbr\\Desktop\\test.txt")) {
// Read bytes from fin.
...
} catch (IOException e) {
// handle exception
...
}
It does compile because the ShowFile2 class contains return in the catch block: this will ensure that the variable fin will be always initialized.
In the first class you caught the exception and you continue the execution of your program.
I'm trying to close a RandomAccessFile but resource remain busy.
Code:
public boolean isOpen(RandomAccessFile f) {
try {
f.length() ;
return true ;
}
catch (IOException e) {
return false ;
}
}
this.rfmFile = new File(filePath);
try {
this.rfmRandomAccessFile = new RandomAccessFile(rfmFile, "rws");
} catch(Exception e){
}finally{
this.rfmRandomAccessFile.close();
}
while(!isOpen(this.rfmRandomAccessFile));
log.debug("I Finally Closed this RAF");
Log is not showed and thread goes in loop.
When I try to access to my resource from shell it gives me "Device or Resource busy".
The only way to access is kill java process.
When you are trying to access the RandomAccessFile length(), method, it is already closed and thus you cannot access it anymore.
You probably want to use the length() method of File. Your loop cannot work as the RandomAccessFile was already closed.
But I must admit I am clueless on the low level reason why rfmRandomAccessFile would not really be closed. It could be a side effect of your strange loop trying to get the size of a closed file.
[edit:]Could not reproduce your issue with the following piece of code:
package com.company;
import java.io.*;
public class Main {
public static void main(String[] args) {
File file = new File("foobar.txt");
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rws");
randomAccessFile.write(new byte[]{'f'});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(randomAccessFile !=null){
try {
randomAccessFile.close();
} catch (IOException e) {
//doh!
}
}
}
FileReader reader = null;
try {
reader = new FileReader(file);
char read = (char) reader.read();
System.out.println("what was written: "+read);
System.out.println("file size: "+file.length());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader !=null){
try {
reader.close();
} catch (IOException e) {
//doh!
}
}
}
}
}
I have to build a chat program.
There is the server class, the client class and two threads to write and receive messages.
the two threads should run in an infinite loop and check all the time if there is an input and print that input afterwards.
But my program works for just one round. So the server and the client can write one single message, afterwards it stops and does not check for another message. Why does the thread not start again from the begin when it's never interrupted? --> see the code beneath
I hope you know what my problem is, it's quite hard for me to describe.
Thread to read a new Message
public class MsgWriter extends Thread {
private Socket s;
public MsgWriter(Socket s){
this.s = s;
}
public void run(){
int i = 0;
OutputStream out = null;
PrintWriter writer;
Scanner input;
while(!interrupted()){
try{
synchronized(s){
input = new Scanner (System.in);
out = s.getOutputStream();
writer = new PrintWriter(out);
String toserver = input.nextLine();
writer.write(toserver);
writer.flush();
System.out.println("me: " + toserver);
}
try {
Thread.sleep((int) (100 * Math.random()));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(Exception e) {
}
}
}
}
Thread to check if there is a new message and prints it.
public class MsgReader extends Thread {
Socket s;
public MsgReader(Socket s){
this.s = s;
}
public void run() {
int i = 0;
while (!interrupted()) {
try{
synchronized(s){
InputStream in = s.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String s = null;
while((s=reader.readLine()) != null){
System.out.println("d");
}
}
try {
Thread.sleep((int) (100 * 1));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch (Exception e){
}
}
}
}
The Server class starts a new server and waits for a client, afterwards it starts the two threads. The same with the client class, it connects to the server and starts the threads.
You're probably thowing an exception somewhere. In your catch blocks, print the error.
try {
} catch (Exception e) {
System.out.println("Error: " + e);
}
My program is basically a daily planner.
The schedule is saved in files by month and year by ObjectOutputStream. check
The schedule is arranged in an array by day. check
The schedule is retrieved by ObjectInputStream. This is where I have problems.
public class Calendar {
public String date;
public String[] schedule = new String[31];
Calendar(){
}
public String retrieve(int month, int day, int year) {
date = Integer.toString(month) + "-"+ Integer.toString(year ) + ".txt";
try {
ObjectInputStream input = new ObjectInputStream(new
FileInputStream(date));
input.readObject();
schedule = input;
//This is where I have the error obviously schedule is a string array and
//input is an ObjectInputStream so this wont work
input.close();
return schedule[day-1];
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "File not found";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "IOException";
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "ClassNotFound";
}
}
public void save(int month, int day, int year, JTextArea entry) {
date = Integer.toString(month) + "-"+ Integer.toString(year ) + ".txt";
schedule[day-1]= entry.getText();
try {
ObjectOutputStream output = new ObjectOutputStream(new
FileOutputStream(date ));
output.writeObject(schedule);
output.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The schedule will be displayed in a text area using something like
entry.setText(calendar.retrieve(month,day,year));
ObjectInputStream input = new ObjectInputStream(new FileInputStream(date));
OK.
input.readObject();
Pointless. This method returns the object that was read. You need to store it into a variable.
schedule = input;
Also pointless. input is an ObjectInputStream that you're about to close. Saving it in another variable is futile.
//This is where I have the error obviously schedule is a string array and
//input is an ObjectInputStream so this wont work
input.close();
It should be
schedule = (String[])input.readObject();
I want to remove a line from my file (specifically the second line)
so I have used another file to copy in it ,but using the following code the second file contain exactly the same text.(My original file .txt and my final file .xml)
public static File fileparse() throws SQLException, FileNotFoundException, IOException {
File f=fillfile();//my original file
dostemp = new DataOutputStream(new FileOutputStream(filetemp));
int lineremove=1;
while (f.length()!=0) {
if (lineremove<2) {
read = in.readLine();
dostemp.writeBytes(read);
lineremove++;
}
if (lineremove==2) {
lineremove++;
}
if (lineremove>2) {
read = in.readLine();
dostemp.writeBytes(read);
}
}
return filetemp;
}
You do not read the line if the lineremove is 2 and also you check if it is greater than 2 after you increased it when it was 2. Do it like this:
int line = 1;
String read = null;
while((read = in.readLine()) != null){
if(line!=2)
{
dostemp.writeBytes(read);
}
line++;
}
you can use BufferedReader with the readLine() method to read line by line, check if it a line you want and skip the lines you dont want.
check the docs at: BufferedReader
here is a working example (Not the most beautiful or clean :) ):
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("d:\\test.txt"));
} catch (FileNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
PrintWriter out = null ;
try {
out = new PrintWriter (new FileWriter ("d:\\test_out.txt"));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String line = null;
int lineNum = 0;
try {
while( (line = in.readLine()) != null) {
lineNum +=1;
if(lineNum == 2){
continue;
}
out.println(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out.flush();
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}