Java URL Connection blank input stream - java

The application I am working on has a terribly slow loading web page. If I run the following code it works fine but only because of the call to sleep. If I don't sleep then the InputStream is just a bunch of spaces, probably due to the application it is calling from. Is there any non-hack way around this?
public class PublishTool extends Thread {
private URL publishUrl;
private String filerLocation;
public PublishTool() {
}
public PublishTool(String publishUrl, String filerLocation) throws NibException {
try {
this.publishUrl = new URL(publishUrl);
} catch (MalformedURLException e) {
throw new NibException("Publish Url :" + publishUrl + " is not valid. ");
}
this.filerLocation = filerLocation;
}
public void run() {
File filerFile = new File(filerLocation);
BufferedWriter writer = null;
try {
URLConnection conn = publishUrl.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));
writer = new BufferedWriter(new FileWriter(filerLocation));
Thread.sleep(1000l);
while (reader.ready()) {
writer.write(reader.readLine() + "\n");
}
} catch (MalformedURLException e) {
throw new IllegalStateException("Malformed URL for : " + publishUrl + " " + filerLocation, e);
} catch (IOException e) {
throw new IllegalStateException("IO Exception for : " + publishUrl + " " + filerLocation, e);
} catch (InterruptedException e) {
throw new IllegalStateException("Thread was interrupted early... publishing might have failed.");
} catch (NibException e) {
throw new IllegalStateException("Publishing File Copy failed : " + filerLocation + ".bak" + " to " + filerLocation);
} finally {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Don't use reader.ready(). Just call readLine() and let readLine() block until the data's ready. The end of the data will generally be signalled with a null line.
In case its helpful, a couple of code examples on my web site: reading from a URL.

Firstly, it would be helpful if you posted your actual code.
My guess the problem is calling Reader.ready. Similar to InputStream.available, that returns true if there is already buffered input. If it needs to wait for, say, a socket the it will return false. Generally you don't need ready. Use readLine, and break out of the loop if it returns null (for end of stream).

Related

Saving input to a file is replaced when re-running

I'm trying to create something similar to a mail server.
Now, I'm supposed to have a file called 'Credentials' that saves the email and password entered each time I run the client.
File Credentials = new File("Server\\Credentials.txt");
try{
if(Credentials.createNewFile()){
System.out.println("Credentials created");
}else {System.out.println("Credentials already exists");}
}catch(Exception error){}
try (
PrintWriter out = new PrintWriter(Credentials, "UTF-8")
) {
out.println("Email: " + email);
out.println("Password: " + password);
} catch(IOException e) {
e.printStackTrace();
}
However, each time a client runs, it replaces the old email and password. Any idea how to make it continue to the next line without replacing? Thank you.
As previously mentioned you have to use the correct constructor, which will append your text instead of overriding.
But I would suggest to do it this way:
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
doSomething("test" + i);
}
}
static void doSomething(String text) {
try (PrintWriter test = new PrintWriter(new BufferedWriter(new FileWriter("your path", true)))) {
test.print(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here are some further informations and different approaches for your issue:
How to append text to an existing file in Java?

create a java server socket that waits for messages from client using Thread Pool

#FXML
private TextArea textarea;
#FXML
private ImageView imagev;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
Serverth Server = new Serverth();
Server.start();
}
class Serverth extends Thread {
#Override
public void run() {
try {
final int NUM_THREAD = 99;
ServerSocket socket = new ServerSocket(8078);
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREAD);
System.out.println("SERVER SOCKET CREATED");
while (!isInterrupted()) {
Socket in = socket.accept();
Runnable r = new ThreadedHandler(in);
exec.execute(r);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
class ThreadedHandler implements Runnable {
private Socket incoming;
public ThreadedHandler(Socket in) {
incoming = in;
}
public void run() {
try {
try {
ObjectInputStream is=new ObjectInputStream(incoming.getInputStream());
while(true) {
if (is.available() > 0) {
String line = is.readUTF();
textarea.appendText("\n" + "[" + new java.util.Date() + "] : " + line);
if (line.contains("inviato")) {
Object obj = is.readObject();
Email ema = (Email) obj;
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy-hh-mm-ss");
FileOutputStream fileOut = new FileOutputStream("src/Server/" + ((Email) obj).getDestinat() + "/" + formatter.format(((Email) obj).getData()) + ".txt");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(ema);
objectOut.flush();
objectOut.close();
System.out.println("The Object was succesfully written to a file");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
} catch(IOException ex) {
ex.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
incoming.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Inside the run method (in Serveth class), I create a server socket and call exec.execute method.
Inside the run method (in ThreadedHandler class), the server is waiting for messages from the client (in this specific case, it creates a new .txt file but it is not important).
Everything works but causes excessive use of the CPU and lag!!!
InputSteam.available method returns a value instantly, telling you no bytes are available to be read, so this code runs a very "hot" spin loop:
while(true) {
if (is.available() > 0) {
...
}
}
The available method is rarely useful and often gives confusing results (see for example inputstream.available() is 0 always). I would suggest you get rid of the if statement altogether:
while(true) {
String line = is.readUTF();
textarea.appendText("\n" + "[" + new java.util.Date() + "] : " + line);
...
}
There's no way for this your code to exit the loop normally. You may want to add a mechanism for the client to disconnect from the server.

Problem with deserialization from object file to field

my problems is that I don't really know why the object is not saving in the field of my class, I'm doing some small star management program for Semestral project for Programming in Java. So my question is why when object deserialize correctly but don't save in the field. Is there a possibility that the fields in the object file are empty?
private void setConstellation(Constellation constellation) {
Object obj;
File constellationFile = new File("src\\Constellations\\" + constellation.getNazwa() + ".obj");
boolean constellationExist = constellationFile.exists();
if(constellationExist == true) {
try {
ObjectInputStream loadStream = new ObjectInputStream(new FileInputStream("src\\Constellations\\" + constellation.getNazwa() + ".obj"));
while ((obj = loadStream.readObject()) != null) {
if (obj instanceof Constellation && ((Constellation) obj).getNazwa().equals(constellation.getNazwa())) {
this.constellation = constellation;
}
}
} catch (EOFException ex) {
System.out.println("End of file");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
else if(constellationExist == false){
try{
ObjectOutputStream saveStream = new ObjectOutputStream(new FileOutputStream("src\\Constellations\\" + constellation.getNazwa() + ".obj"));
saveStream.writeObject(constellation);
this.constellation = constellation;
}
catch (IOException e){
e.printStackTrace();
}
}
}
While debugging this part of program, the while loop in first if don't event check :/
Can you help me somehow?
You should call saveStream.close() after writing the object to ensure that the stream is properly flushed.
You should also close the loadStream.
If you're on Java 7 or newer, you can use try-with-resources:
try (ObjectOutputStream saveStream = new ObjectOutputStream(
new FileOutputStream("src\\Constellations\\" +
constellation.getNazwa() + ".obj"))) {
saveStream.writeObject(constellation);
this.constellation = constellation;
} catch (IOException e){
e.printStackTrace();
}
This construct ensures that the stream is closed when you exit the try block.

BufferedWriter stops writing to file after a while

I've found a bunch of similiar questions there, but all the proposed solutions already exist in my code, so...
I have the following routine being called from different places in my app:
static private void writeToFile(String data) {
File file = new File("sdcard/output.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter bw = null;
try {
FileWriter fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
bw.append(new Date().toString() + " " + data);
bw.newLine();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(bw != null) {
bw.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
Sometimes after a while strings stop to be added to a file. I've presumed it's something about syncronization - but once I've succeeded to catch it in debug mode and stepped all over the routine - every statement is executed without any exceptions.
Can you, please, tell what's wrong with my code?

Resources not getting released in java

So, I have a function that reads file data, in this case image size. But after it's done it doesn't seem to properly release the files. I can't move those files afterwards. If I don't call this function everything works, but if I do I always get "file in use.. blah blah blah"
private void setMoveType() {
ImageInputStream in = null;
try {
in = ImageIO.createImageInputStream(new FileInputStream(file.toString()));
try {
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if(readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(in);
try {
moveType = Helper.getMoveType(new Dimension(reader.getWidth(0), reader.getHeight(0)));
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
} catch(Exception e) {
System.err.println("ReaderException: " + e.getMessage());
} finally {
reader.dispose();
}
}
} catch(Exception e) {
System.err.println("MoveTypeSetException: " + e.getMessage());
}
} catch (IOException e) {
System.err.print("IOException: failure while creating image input stream");
System.err.println(" -> createImageInputStream Error for file: " + file.getFileName());
return;
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
}
}
}
EDIT: The ImageInputStream doesn't close properly
EDIT2: a FileInputStream wasn't closed
This stream should also be closed:
new FileInputStream(file.toString())
Closing the stream when you are done should work (in.close()). The operating system prevents the file from being changed, deleted or moved while it is in use. Otherwise, the stream would get messed up. Closing the stream tells the operating system you are no longer using the file.

Categories