Creating and writing file from a FileOutputStream in Java

Posted by Althane on Stack Overflow See other posts from Stack Overflow or by Althane
Published on 2010-04-27T16:17:33Z Indexed on 2010/04/27 16:43 UTC
Read the original article Hit count: 296

Filed under:
|
|

Okay, so I'm working on a project where I use a Java program to initiate a socket connection between two classes (a FileSender and FileReceiver). My basic idea was that the FileSender would look like this:

  try {
 writer = new DataOutputStream(connect.getOutputStream());
} catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}

 //While we have bytes to send
 while(filein.available() >0){
 //We write them out to our buffer
writer.write(filein.read(outBuffer));
writer.flush();
 }
 //Then close our filein
 filein.close();
 //And then our socket;
 connect.close();
} catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();

The constructor contains code that checks to see if the file exists, and that the socket is connected, and so on. Inside my FileReader is this though:

 input = recvSocket.accept();
 BufferedReader br = new BufferedReader(new InputStreamReader(input.getInputStream()));
 FileOutputStream fOut= new FileOutputStream(filename);
 String line = br.readLine();
 while(line != null){
  fOut.write(line.getBytes());
  fOut.flush();
  line = br.readLine();
 }
 System.out.println("Before RECV close statements");
 fOut.close();
 input.close();
 recvSocket.close();
 System.out.println("After RECV clsoe statements");

All inside a try-catch block. So, what I'm trying to do is have the FileSender reading in the file, converting to bytes, sending and flushing it out. FileReceiver, then reads in the bytes, writes to the fileOut, flushes, and continues waiting for more. I make sure to close all the things that I open, so... here comes the weird part.

When I try and open the created text file in Eclipse, it tells me "An SWT error has occured ... recommended to exit the workbench... see .log for more details.". Another window pops up saying "Unhandled event loop exception, (no more handles)". However, if I try to open the sent text file in notepad2, I get

ThisIsASentTextfile

Which is good (well, minus the fact that there should be line breaks, but I'm working on that...). Does anyone know why this is happening? And while we're checking, how to add the line breaks?

(And is this a particularly bad way to transfer files over java without getting some other libraries?)

© Stack Overflow or respective owner

Related posts about java

Related posts about file-io