在Java中从FileOutputStream创建和写入文件

在Java中从FileOutputStream创建和写入文件

本文介绍了在Java中从FileOutputStream创建和写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我正在开发一个项目,我使用Java程序在两个类之间启动套接字连接( FileSender FileReceiver )。我的基本想法是 FileSender 看起来像这样:

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();

构造函数包含检查文件是否存在以及套接字是否已连接的代码,以及等等。在我的FileReader里面就是这样:

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");

所有在try-catch块内。所以,我要做的是在文件中读取 FileSender ,转换为字节,发送和刷新它。 FileReceiver ,然后读入字节,写入fileOut,刷新,并继续等待更多。我确保关闭所有打开的东西,所以...这里有一些奇怪的部分。

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.

当我尝试在Eclipse中打开创建的文本文件时,它告诉我SWT错误已经发生......建议退出工作台...有关详细信息,请参阅.log。弹出另一个窗口,说未处理的事件循环异常,(不再处理)。但是,如果我尝试在notepad2中打开发送的文本文件,我会得到

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?

(这是一种特别糟糕的方式来通过java传输文件而无需获取其他库吗?)

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

编辑:更新:我将代码更改为以下(FileReceiver),而不更改发件人:

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();
    }

这是有效的。我得到一个大小合适的文本文件(在获得4Kb标准大小之前),并且具有正确的格式。我将在接下来的图像上尝试它,并让你更新。

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.

推荐答案

乍一看:你为什么使用?
完全不适合你的目标。只需使用您提供的输出流:

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

writer = connect.getOutputStream();

顺便说一句,将作家称为变量,这是一个可疑的做法,Java在读者之间产生明显的概念差异/ writers(面向字符)和流(面向字节)。

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

更新:另一个不好的做法,它需要麻烦:你是混合读者/作者(面向字符)和不必要的流(面向字节) - 并且没有指定charset编码。

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()));

在处理文本时(必须使用已知编码),必须使用Reader,使用InputStream如果你只处理字节。

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.

这篇关于在Java中从FileOutputStream创建和写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:29