Why in the readFile2() I need to catch the FileNotFoundException and later the IOException that is thrown by the close() method, and in the try-with-resources(inside readfile1) Java doesn't ask me to handle the FileNotFoundException, what happened?
public class TryWithResourcesTest {
public static void main(String[] args) {
}
public static void readFile1() {
try(Reader reader = new BufferedReader(new FileReader("text.txt"))) {
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readFile2() {
Reader reader = null;
try {
reader = new BufferedReader(new FileReader("text.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if(reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileNotFoundException is a subclass of IOException. By catching the latter, you're catching the former too. It has nothing to do with try-catch vs. try-with-resources.
Related
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!
}
}
}
}
}
try {
FileWriter fw = new FileWriter("plugins/TestMessage/messages.txt", true);
} catch (IOException e) {
e.printStackTrace();}
}
Hey guys, I know this may sound noobish but how do I close this FileWriter. The code is in java. I have an onDisable() method that gets called when the server is stopped but when I put fw.close(); It says fw cannot be resolved. Please help!
The relevant section of the code is
public class MAIN extends JavaPlugin{{
try {
FileWriter fw = new FileWriter("plugins/TestMessage/messages.txt", true);
} catch (IOException e) {
e.printStackTrace();}
}
public void onEnable(){
Logger.getLogger("Minecraft").info("MessageBroadcaster made by cheeseballs500 aka weakwizardsucks2");
}
public void onDisable(){
fw.close();//fw cannot be resolved
}
EDIT: Fixed :D
Try creating the FileWriter outside of any methods, then setting it to something in your onEnable()... Here's an example:
public class Main extends JavaPlugin{{
FileWriter fw;//create the variable
#Override
public void onEnable(){
try{
fw = new FileWriter(this.getDataFolder() + "/messages.txt", true); //assign the variable to a value, and put the file in your plugin's folder
}
catch(IOException e){
e.printStackTrace();
}
}
#Override
public void onDisable(){
try{ //try-catch just incase
fw.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Try this..
public class MAIN extends JavaPlugin{
public MAIN() {
try {
this.fw = new FileWriter("plugins/TestMessage/messages.txt", true);
} catch (Exception e) {
// TODO: handle exception
}
}
FileWriter fw = null;
public void onEnable(){
Logger.getLogger("Minecraft").info("MessageBroadcaster made by cheeseballs500 aka weakwizardsucks2");
}
public void onDisable(){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//fw cannot be resolved
}
}
I have no idea why I get the message "cannot be resolved" on out in eclipse on the 11th line
import java.io.*;
public class driver {
public static void main(String[] args) {
try {
PrintWriter out = new PrintWriter("output.txt");
}
catch (FileNotFoundException e) {
System.out.print("file not found");
e.printStackTrace();
}
out.print("hello");
out.close();
}
}
OK so now I have this
import java.io.*;
public class driver {
public static void main(String[] args) {
PrintWriter out = null;
try {
out = new PrintWriter("output.txt");
}
catch (FileNotFoundException e) {
System.out.print("file not found");
e.printStackTrace();
}
out.print("hello");
out.close();
}
}
Why doesn't eclipse create a file once I close out?
Declare your PrintWriter before the try block so it's scope isn't limited to the try block.
You can also use new try-with-resource block introduced in JDK 1.7, in this advantage is you don't need to worry about closing any resource which implements Closable Interface.
Then code will look like this:
try (PrintWriter out = new PrintWriter("output.txt"))
{
out.print("hello");
}
catch (FileNotFoundException e)
{
System.out.print("file not found");
e.printStackTrace();
}
I am trying to access the
public static List<ChatThread> Chat_list of my ChatThread Class
from the run() method of my Client Class but i keep getting an empty array(Infact it throws an exception at that point : Exception in thread "Thread-2" java.lang.NullPointerException)
and am very certain that that arrayList exists and is not empty(Because i did a test on the arrayList in my ChatThread Class). Just take a look at my code.
Please I need your help on what to do.
Thanks.
This is the class containing the arrayList :
public class ChatThread extends Thread {
private Socket sc;
private String cherry_name;
private String passwd;
public static List<ChatThread> Chat_list = new ArrayList<ChatThread>(); //THE STATIC ARRAY LIST
private BufferedReader br;
private BufferedWriter bw;
public ChatThread(Socket sc){
try {
this.sc=sc;
System.out.println(sc);
br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(sc.getOutputStream()));
String help = br.readLine();
this.cherry_name=help.split("#")[0];
this.passwd=help.split("#")[1];
System.out.println(this.cherry_name);
System.out.println(this.passwd);
Chat_list.add(this); //This is where i add it to the arrayList
if(Chat_list.isEmpty()) //This is where i did the test
System.out.println("I am empty");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run(){
//Comparaison of information with that in the database
try{
bw.write("success");
bw.newLine();
bw.flush();
while(true){
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Socket getSc() {
return sc;
}
public String getCherry_name() {
return cherry_name;
}
}
As for the Client class :
public class Client extends Thread {
private Socket socket;
private BufferedReader br;
private BufferedWriter bw;
private ChatThread th;
private String cherry_name;
public Client(String cherry_name,String passwd){
try
{
socket = new Socket("127.0.0.1", 8888);
this.cherry_name=cherry_name;
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(cherry_name+"#"+passwd);
bw.newLine();
bw.flush();
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Erreur lors de la lecture du socket");
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
public void run()
{
try {
String help = br.readLine();
if(help.equals("failed")){
this.notify();
this.destroy();
socket.close();
}
else{
if(ChatThread.Chat_list.isEmpty()) System.out.println("Empty array!!!"); //This is where it says the array is empty whereas it wasn't the case in the ChatThread Class
for(ChatThread ct : ChatThread.Chat_list){
if(cherry_name.equals(ct.getCherry_name())){
th=ct;
break;
}
}
while(true){
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error whilst reading from the socket");
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Interruption");
e.printStackTrace();
}
}
public Socket getSocket() {
return socket;
}
}
And my server class :
public class Server {
public static void main(String[] args) {
try {
ServerSocket server =new ServerSocket(8888);
Socket sc;
System.out.println("Server Started");
while(true){
sc=server.accept();
System.out.println("New Connection");
new ChatThread(sc).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A main class to instantiate the Client class :
public class help {
public static void main(String[] argv) {
new Client("Jerry","Smith").start();
}
}
Every access to a mutable object shared between two threads must be accessed in a synchronized way. Not synchronizing will lead to visibility and coherence issues like you're seeing.
You should not expose an ArrayList like that (even without multiple threads, public static mutable objects are already a very bad practice). Instead, you should encapsulate it in your own object, and make sure every access is synchronized properly.
It's hard to give a more concrete advice without seeing any line of your code.
I'm trying to implement multiplayer in a game I've been writing, and I've gotten everything to successfully connect (I think..), but when I'm running it, there's an EOFException thrown by the client, and the object (an ArrayList) isn't successfully received.
Code for the server thread:
class ServerThread implements Runnable
{
ServerSocket server = null;
Socket controlSocket = null;
ObjectOutputStream outStream = null;
ObjectInputStream inStream = null;
#Override
public void run() {
setupConnection();
while(true){
sendObject(out.getStuff());
}
}
void setupConnection(){
Log.e("OUTPUTSHOOTER","init-connect");
try {
server = new ServerSocket(SERVERPORT);
Log.e("OUTPUTSHOOTER","server initiated port: "+SERVERPORT);
controlSocket = server.accept();
Log.e("OUTPUTSHOOTER","connected");
inStream = new ObjectInputStream(controlSocket.getInputStream());
outStream = new ObjectOutputStream(controlSocket.getOutputStream());
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("OUTPUTSHOOTER",server+" "+controlSocket+" "+inStream+" "+outStream);
}
public Object recieveObject(){
Object o = null;
try {
o = inStream.readObject();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return o;
}
public void sendObject(Object o)
{
try {
outStream.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And then the code for the client:
class ClientThread implements Runnable
{
Socket controlSocket = null;
ObjectOutputStream outStream = null;
ObjectInputStream inStream = null;
#Override
public void run() {
setupConnection();
while(true){
Log.e("OUTPUTSHOOTER","recieving");
Object in = recieveObject();
if(in!= null && in instanceof ArrayList)
{
Log.e("OUTPUTSHOOTER","loading");
out.load((ArrayList<UniverseObject>)in);
}
}
}
void setupConnection(){
Log.e("OUTPUTSHOOTER","ip: "+SERVERIP);
while(controlSocket == null) {
try {
controlSocket = new Socket(SERVERIP,SERVERPORT);
Log.e("OUTPUTSHOOTER","socket connected");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Log.e("OUTPUTSHOOTER","attempting streams");
outStream = new ObjectOutputStream(controlSocket.getOutputStream());
Log.e("OUTPUTSHOOTER","output working");
inStream = new ObjectInputStream(controlSocket.getInputStream());
Log.e("OUTPUTSHOOTER","streams connected");
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object recieveObject(){
Object o = null;
try {
o = inStream.readObject();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return o;
}
public void sendObject(Object o)
{
try {
outStream.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What does this mean? And perhaps more importantly, how can I fix it? Thanks in advance..
I don't see you closing your outputstream.
See this SO topic: Problem serializing and deserializing ArrayList
Turns out the server wasn't properly initiating it's input and output streams, even though its sockets were successful. Dunno why, but it only works if I started with the output stream first, then the input (?). Having some other really strange bugs, but at least the communication seems to work.. I'll look more in to them before posting here about it. Thanks guys!