Creating and writing file from a FileOutputStream in Java

回眸只為那壹抹淺笑 提交于 2019-12-01 10:16:02

问题


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?)

Edit: An update: I changed my code to the following (FileReceiver), without changing the sender:

    try {
        input = recvSocket.accept();
        //InputStream br = new InputStream(input.getInputStream());
        FileWriter fOut= new FileWriter(filename);
        //BufferedWriter out = new BufferedWriter(fOut);
        //String line = br.
        byte info = (byte) input.getInputStream().read();
        while((int)info != 0){
            fOut.write(info);
            fOut.flush();
            info = (byte) input.getInputStream().read();
        }
        fOut.flush();
        System.out.println("Before RECV close statements");
        fOut.close();
        //input.close();
        recvSocket.close();
        System.out.println("After RECV clsoe statements");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

This works. I get a text file that is the right size in bytes (before I was getting 4Kb standard size), and has the right formatting. I'm going to try it on an image next, and keep you updated.


回答1:


From a first glance: Why are you using a DataOutputStream ? Totally inadequate for your goal. Just use your provided outputstream:

writer = connect.getOutputStream();

BTW, it's dubious practice to call "writer" that variable, Java makes a clear conceptual difference between readers/writers (char oriented) and streams (byte oriented).

UPDATE: Another bad practice, which calls for trouble: you are mixing readers/writers (char oriented) and streams (byte oriented) unnecessarily - and without a specifyng a charset encoding.

BufferedReader br = new BufferedReader(new InputStreamReader(input.getInputStream()));

You must use a Reader when you are dealing with text (in a know encoding), use a InputStream if your are just dealing with bytes.




回答2:


If you want to open reports after exporting/saving it, then this will definately work

       JasperReportBuilder report = DynamicReports.report();// a new report
       report.setDataSource(dataSource);

        String path = "d:\\PriceReport"+Math.random()+".pdf";
        File generatedfile= new File(path);
        FileOutputStream fileOutStream = new FileOutputStream(generatedfile);
        report.toPdf(fileOutStream);
        fileOutStream.close();
        fileOutStream.flush();
         if(generatedfile.exists()){
             if(Desktop.isDesktopSupported()){
                Desktop.getDesktop().open(generatedfile);
             }else{
                System.out.println("Not Supported by your desktop");
             }
         }else{
             System.out.println("File does not Exists");
         }



回答3:


Regarding line breaks, BufferedReader.readLine() reads data, terminated by a line feed, but it doesn't return the line feed. So, when you write it back out, you'll want to write a line feed. Alternatively, you can read and write bytes, so you don't end up mistakenly converting line feed characters or corrupting binary files that include the ascii values for line feed or carriage return.



来源:https://stackoverflow.com/questions/2722934/creating-and-writing-file-from-a-fileoutputstream-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!