开发者

PHP and a file written by Java FileOutputStream

开发者 https://www.devze.com 2023-01-24 09:17 出处:网络
I have a text file that is written by Java FileOutputStream. When i read that file using file_get_contents, then everything is on same line and there are no separators between different str开发者_JAV

I have a text file that is written by Java FileOutputStream.

When i read that file using file_get_contents, then everything is on same line and there are no separators between different str开发者_JAVA百科ings. I need to know, how to read/parse that file so i have some kind on separators between strings

I'm using somethig like this, to save the file:

Stream stream = new Stream(30000, 30000);
stream.outOffset = 0;
stream.writeString("first string");
stream.writeString("second string");

FileOutputStream out = new FileOutputStream("file.txt");
out.write(stream.outBuffer, 0, stream.outOffset);
out.flush();
out.close();
out = null;


I have no idea what that Stream thing in your code represents, but the usual approach to write String lines to a file is using a PrintWriter.

PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream("/file.txt"), "UTF-8"));
writer.println("first line");
writer.println("second line");
writer.close();

This way each line is separated by the platform default newline, which is the same as you obtain by System.getProperty("line.separator"). On Windows machines this is usually \r\n. In the PHP side, you can then just explode() on that.


file_get_contents returns the content of the file as a string. There are no lines in a string.

Are you familiar with newlines? See wikipedia

So, what you are probably looking for is either reading your file line for line in PHP, or reading it with file_get_contents like you did and then explode-ing it into lines (use "\n" as separator).


There is no indication in your code that you are writing a line separator to the output stream. You need to do something like this:

String nl = System.getProperty("line.separator");

Stream stream = new Stream(30000, 30000);
stream.outOffset = 0;
stream.writeString("first string");
stream.writeString(nl);
stream.writeString("second string");
stream.writeString(nl);

FileOutputStream out = null;

try
{
    out = new FileOutputStream("file.txt");
    out.write(stream.outBuffer, 0, stream.outOffset);
    out.flush();
}
finally
{
    try
    {
        if (out != null)
            out.close();
    }
    catch (IOException ioex) { ; }
}

Using PHP, you can use the explode function to fill an array full of strings from the file you are reading in:

<?php

    $data = file_get_contents('file.txt');
    $lines = explode('\n', $data);

    foreach ($lines as $line)
    {
        echo $line;
    }

?>

Note that depending on your platform, you may need to put '\r\n' for the first explode parameter, or some of your lines may have carriage returns on the end of them.

0

精彩评论

暂无评论...
验证码 换一张
取 消