Java Material
Pfad: Startseite / Fächer / Informatik / Java
Autor: mk
03.11.2010 16:25
5229
Java

Programm 1 - das "Hallo Welt" - Programm

public class p1
{

  public static void main(String[] args)
  {
     System.out.println("Hallo Welt!");
  }
}

Programm 3 - eingeben und wieder ausgeben

aus Java ist auch eine Insel Openbook von Christian Ullenboom, Listing 12.11

  public class KonsolenHinUndHer
{
  public static void main( String args[] )
  {
    System.out.println( "\nGib mir eine Zeile Text: " );
    byte buffer[] = new byte[255];
    try
    {
      System.in.read( buffer, 0, 255 );
    }
    catch ( Exception e )
    {
      System.out.println( e );
    }
    System.out.println( "\nDu hast mir gegeben: ");
    System.out.println( new String(buffer) );
  }
}

Programm 4 - Bytes aus Datei einlesen und ausgeben

import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;


public class BytesDatei
{
  public static void main( String args[] ) throws IOException
  {
    File f = new File( args[0] ); 
    int L = (int) f.length();
    byte[] buffer = new byte[L]; 
    InputStream in = new FileInputStream( f ); 
    in.read( buffer ); 
    in.close();
    System.out.println( new String(buffer) );
    System.out.println( buffer );
    for ( int i = 0; i < L; i ++ ) 
    {
      System.out.println( buffer[i] );
    }
  }
}

Eine Datei t.xyz, die die Bytes

41 C3 B6 E2 82 AC 0A 61 62 63

enthält, führt zu der Ausgabe

Aö€
abc
[B@4a5ab2
65
-61
-74
-30
-126
-84
10
97
98
99

Es stellt sich die Frage, wie Java zu [B@4a5ab2 kommt und wieso die Bytes des Puffers teilweise negativ ausgegeben werden.

Das zweite Byte C3 hat ein gesetztes höchstes Bit. Interpretiert man das als Vorzeichen und ermittelt man das Zweierkomplement, so ergibt sich tatsächlich -61. Dh. Bytes werden als vorzeichenbehaftete 1-Byte-Integer ausgegeben. Das passt zu diesem Link. Verändert man die letzte Schleife zu

for ( int i = 0; i < L; i ++ ) 
    {
      int b = buffer[i]; 
      if ( b < 0 ) b = b + 256; 
      System.out.println( b );
    }

so werden die Werte der Bytes korrekt ausgegeben.

Versuche mit Text

import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.String;


public class TextDatei
{
  public static void main( String args[] ) throws IOException
  {
    File f = new File( args[0] ); 
    int L = (int) f.length();
    byte[] buffer = new byte[L]; 
    InputStream in = new FileInputStream( f ); 
    in.read( buffer ); 
    in.close();
    /*
    String s;
    s = (String) buffer;
    */
    String s = new String(buffer,"UTF-16"); 
    System.out.println( s );
    System.out.println( new String(buffer) );
    System.out.println( buffer );
    for ( int i = 0; i < L; i ++ ) 
    {
      System.out.println( buffer[i] );
    }
  }
}

Links

TextDatei.java, t2.txt