0

First of all I read many about this question. However none of them was my solution. I am trying to read string from console and write it to the .txt as byte.

I tried FileWriter/BurfferWriter. But ,for example, I am typing "abcd" from console, then I made it as byte[]. And in the for loop I wrote it in the txt file. These seems OK. However, when I looked at the txt file, I saw that it was written as normal, "abcd". I was expecting it to be writen something like http://s24.postimg.org/uid0tt0g5/byte.png I do not want any one to read my .txt file when s/he opens it.

Then, I tried to RandomAccessFile. At this time, I coded something like that:

for(int i=0; i<tableName.length(); i++){
    file.writeChar(tableName.charAt(i));
}

however at this time, it writes the abcd as http://s14.postimg.org/j1k26qqnx/byte2.png As you see, a b c d is between the bytes. And normally, abcd is only 4 bytes, and when I wrote it in the .txt, txt file becomes 8 bytes.

This is the problem. I do not want to see any char in the txt file.

What is the solution? Thank you

Burak Keceli
  • 933
  • 1
  • 15
  • 31
  • The letter "a" as a byte is still "a". Are you talking about encrypting your text file? – Jon Lin Apr 08 '13 at 11:27
  • If it is still "a", then why does it write as [NUL]a[NUL]b[NUL]c[NUL]d in my second try, using RandomAccessFile? I think what I am looking for is not encryption, because when I give my txt file to others, they have to read it using readByte or something like that. If I encrypt it, I need to tell them also which encryption that I used. – Burak Keceli Apr 08 '13 at 11:32
  • 2
    Because [RandomAccessFile.writeChar(int)](http://docs.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html#writeChar(int)) writes a **2 byte value**, high byte first, and you're only providing the lower byte. – Jon Lin Apr 08 '13 at 11:36
  • so you are saying that, if I want to insert only 512 byte length string, then in the .txt file it is going to be 1024 byte at total. – Burak Keceli Apr 08 '13 at 11:45
  • Please read http://www.joelonsoftware.com/articles/Unicode.html. There is no such thing as byte[] = String, the meaning of characters depend normally on the *encoding*. Java in this case encodes characters as 2-byte UTF-16 encoding. The exception are 8-bit codes depending on ASCII like your a,b,c,d characters which are almost always identical. What do you need is an InputStreamReader and an OutputStreamWriter which converts byte[] to an encoding. – Thorsten S. Apr 08 '13 at 11:49
  • I see, I will check it. Now I wonder that is there any way to write a bit to the txt file? I want to just write 1 or 0 but the length will be 1 bit. – Burak Keceli Apr 08 '13 at 11:55
  • No, any disk I/O hardware can store only data as sequences of bytes. – Thorsten S. Apr 08 '13 at 11:58

0 Answers0