Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add New Line while writing byte array to file

Tags:

c#

Hi I am reading a audio file into a byte array. then i want to read every 4 bytes of data from that byte array and write it into another file.

I am able to do this but, my problem is i want to add new line aft every 4 byte of data is written to file. how to do that?? Here is my code...

FileStream f = new FileStream(@"c:\temp\MyTest.acc");
for (i = 0; i < f.Length; i += 4)
{
    byte[] b = new byte[4];
    int bytesRead = f.Read(b, 0, b.Length);

    if (bytesRead < 4)
    {
        byte[] b2 = new byte[bytesRead];
        Array.Copy(b, b2, bytesRead);
        arrays.Add(b2);
    }
    else if (bytesRead > 0)
        arrays.Add(b);

    fs.Write(b, 0, b.Length);
}

Any suggestions please.

like image 881
Tim Avatar asked Oct 18 '12 08:10

Tim


People also ask

How do I write a byte array to a file?

In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

How to store byte array as String?

Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .


2 Answers

Pass System.Environment.NewLine to the filestream

For more info http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx

like image 94
Boomer Avatar answered Oct 23 '22 23:10

Boomer


I think this might be the answer to your question:

            byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
            fs.Write(newline, 0, newline.Length);

So your code should be something llike this:

            FileStream f = new FileStream("G:\\text.txt",FileMode.Open);
            for (int i = 0; i < f.Length; i += 4)
            {
                byte[] b = new byte[4];
                int bytesRead = f.Read(b, 0, b.Length);

                if (bytesRead < 4)
                {
                    byte[] b2 = new byte[bytesRead];
                    Array.Copy(b, b2, bytesRead);
                    arrays.Add(b2);
                }
                else if (bytesRead > 0)
                    arrays.Add(b);

                fs.Write(b, 0, b.Length);
                byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
                fs.Write(newline, 0, newline.Length);
            }
like image 34
Nikola Davidovic Avatar answered Oct 23 '22 22:10

Nikola Davidovic