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.
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.
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) .
Pass System.Environment.NewLine to the filestream
For more info http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx
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);
            }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With