读取和写入文件时,输出会发生变化

时间:2016-07-21 10:39:26

标签: java file file-writing file-read

我正在尝试读取文件(与扩展名无关)并在此之后写入,但是当我这样做时,输出文件与输入不同。

我的代码是下一个:

OutputStream outputStream = null;
FileReader fr = new FileReader("rute\\inputfile.PNG");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line= br.readLine()) != null) {
    content += line;
}

byte[] toBytes= content.getBytes();
InputStream inputStream = new ByteArrayInputStream(toBytes);
try {
    outputStream = new FileOutputStream(new File("rute\\output.PNG"));
    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    outputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}
inputStream.close();

如果你问我为什么转换成字节并从这个表单写入,是因为我需要对数据做一些事情,我需要这个转换。 如果你告诉我我无法在字符串上加载图像,是的我可以做类似的事情:

File fil = ~~~~;
FileInputStream fis = null;
fis = new FileInputStream(fil);
byte[] bytess = IOUtils.toByteArray(fis);

但我不想这样做,因为如果我想加载大文件,堆大小不够,这可以通过“每行一行”读取来解决。

感谢您的回答

1 个答案:

答案 0 :(得分:2)

我之前建议您阅读this question。由于您正在将二进制数据读入String,因此您正在更改该数据的编码。所以输出会有所不同。

最佳方法是将二进制文件读取为字节数组。但我会依赖你需要做哪种转换/编辑/改变。

<强>更新

当然,您在编写内容之前正在编辑

<?php


//create a solution set for translation of incoming user login requests

$widhi = 600;
$tileDim = 25;
$randArray = array ("0","1","2","3","4","5");
$replyArray = array ();


//create 5 positions and ensure neither overlap or edge collision
class solSet
{
  var $pos1;
  var $pos2;
  var $pos3;
  var $pos4;
  var $pos5;
  var $pos6;


  public function jumble($wh,$ts,$arrShuf,$reply)
  {
    foreach($this as $key => $value)
    {
      $newX = rand (($ts/2),$wh - ($ts/2));
      $newY = rand (($ts/2),$wh - ($ts/2));
      $randNo = array_pop($arrShuf);
      $value = "" . $newX . "_" . $newY . "_" . $randNo;
      $this->$key = $value;
      //push coords onto an array for later ajax
      $pushElem = "" . $newX . "_" . $newY;
      $reply[] = $pushElem;
    }
  }

}


//scramble the random number array for later popping
shuffle($randArray);

//make a solution object
$aSolSet = new solSet;
$aSolSet->jumble($widhi,$tileDim,$randArray,$replyArray);

//store it in a session
session_start();
$_SESSION["solSet"] = $aSolSet;

echo var_dump($replyArray);
echo json_encode($aSolSet);

?>

所以输出文件总是不同。

更新2

由于问题/问题是如何阅读大型二进制文件,google通常是您的朋友。 或者您可以查看其他question