user196106
user196106

Reputation:

PHP and a file written by Java FileOutputStream

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 strings. 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;

Upvotes: 1

Views: 1037

Answers (3)

Chris Hutchinson
Chris Hutchinson

Reputation: 9212

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.

Upvotes: 0

BalusC
BalusC

Reputation: 1109392

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.

Upvotes: 1

Kissaki
Kissaki

Reputation: 9237

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

Upvotes: 0

Related Questions