SoloCodigo

Programación General => Java => Mensaje iniciado por: sergiotarrillo en Miércoles 10 de Noviembre de 2004, 13:11

Título: Urgente: Escribir Cadena Como Bytes
Publicado por: sergiotarrillo en Miércoles 10 de Noviembre de 2004, 13:11
tengo el siguiente codigo par escribir una cadena en un archivo
Código: Text
  1.  public void Write(RandomAccessFile file) throws IOException {
  2.     //escribiendo los datos enviados
  3.     //escribiendo codgio
  4.     file.writeInt(cod);
  5.  
  6.     byte b1[]  = new byte[15];
  7.     //convirtiendo la cadena a byte
  8.     if ( name != null)
  9.       name.getBytes(0,name.length(),b1,0);
  10.     //ahora si escribiend la cadena pero como bytes
  11.     file.write(b1);
  12.  
  13.     //ahora escribiendo la edad
  14.     file.writeInt(edad);
  15.  
  16.   }
  17.  

Pero el problema que cuando escribe algo lo hace asi: Sergio☺☺☺☺

alguien ayuda..........?, tengo examen en la tarde.........  :alien:
Título: Re: Urgente: Escribir Cadena Como Bytes
Publicado por: antony_soluciones en Miércoles 10 de Noviembre de 2004, 22:53
Espero y esto le sirva

import java.io.*;
public class EscribirBytes{
  public static void Write(RandomAccessFile file) throws IOException {
     //escribiendo los datos enviados
     //escribiendo codgio
     for(int i = 1; i<=5; i++)
       file.writeByte(i);//Escribiendo Bytes
     //for(int i = (int)'a'; i<(int)'z';i++)  //si quiere char
     //  file.writeChar((char)i);
  }
  public static void Read(RandomAccessFile file) throws IOException {
    long longitudFichero = 0;
    long puntero;
    int dato = 0;
    longitudFichero = file.length();
    file.seek(0);
    puntero = file.getFilePointer();
    while(puntero<longitudFichero){
      dato = file.readByte();  // Leyendo Bytes
      puntero = file.getFilePointer();
      System.out.println("El entero es: " + dato + "\n");
    }
  }
  public static void main(String[] args) throws IOException {
    File nom = new File("C:\\Archi.txt");
    RandomAccessFile fichero = new RandomAccessFile(nom,"rw");
    EscribirBytes.Write(fichero);
    fichero.close();
    RandomAccessFile ficheroLectura = new RandomAccessFile(nom,"r");
    EscribirBytes.Read(ficheroLectura);
    ficheroLectura.close();
  }
}

Suerte y ojalá esto le llegue a tiempo...