Deprecated: Function set_magic_quotes_runtime() is deprecated in /DISK2/WWW/lokiware.info/mff/wakka.php on line 35 Matfiz : Java / Kousky Kódu
Přihlášení:  Heslo:  
Matfiz: Java/KouskyKódu ...
Hlavní Stránka | Seznam Stránek | Poslední Změny | Poslední Komentované | Uživatelé | Registrace |
Toto je stará verze stránky Java/KouskyKódu z 2009-02-04 00:25:45..

Kousky kódu v Javě

…aneb může se hodit k testu v labu. (Vzhledem k Hnětynkovým podmínkám je třeba si je vytisknout.) Příklady jsou často převzaté z webu Sunu a lehce upravené.

I/O: Čtení slov nebo čísel pomocí scanneru

Zdroj: http://java.sun.com/docs/books/tutorial/essential/io/scanning.html

import java.io.*;
import java.util.Scanner;
/* ... */
Scanner s = null;
try {
    s = new Scanner(new BufferedReader(new FileReader("slova_odd_bilymi_znaky.txt")));

    while (s.hasNext())
        System.out.println(s.next());
} finally {
    if (s != null)
        s.close();
}

import java.io.*;
import java.util.*;
/* ... */
Scanner s   = null;
double  sum = 0;
try {
    s = new Scanner( new BufferedReader(new FileReader("cisla.txt")) );
    s.useLocale(Locale.US);

    while(s.hasNext() ){
        if( s.hasNextDouble() )
            sum += s.nextDouble();
        else
            s.next(); // ignoruje ne-cisla
    }
} finally {
    s.close();
}
System.out.println(sum);

Tip: Pro použití jiných oddělovačů zavolejte s.useDelimiter(regulárnívýraz);, např. s.useDelimiter(",\\s*");, kde \s značí libovolný white space.

Sockety: Jednoduchý server

import java.io.*;
import java.net.*;

public class EchoServer extends Thread {
  private static final int PORT = 12345;
  private static ServerSocket serverSocket;
  private Socket        clientSocket;
  private BufferedReader      is;
  private PrintWriter         os;
  
  public EchoServer(Socket cs) {
    clientSocket = cs;
  }
  
  public static void main(String args[]) {
    try {
      serverSocket = new ServerSocket(PORT);
    } catch (IOException e) {
      System.err.println("Cannot create server socket.");
      System.exit(1);
    }    
    
    for(;;){
      try {
        Socket clientSocket = serverSocket.accept();
        new EchoServer(clientSocket).start();
      }catch (IOException e) {
        System.err.println("Cannot accept client connection.");
      }
    }
  }
  
  public void run() {
    try {
      os = new PrintWriter( new OutputStreamWriter(clientSocket.getOutputStream()) );
      is = new BufferedReader( new InputStreamReader(clientSocket.getInputStream()) );

      String input = null;
      while((input = is.readLine()) != null){
        os.println(input);
        os.flush();
      }
    }catch(IOException e){
      System.err.println("Error while handling a connection.");
    }finally{
      try {
        if (is != null)
          is.close();
        if (os != null)
          os.close();
        if (clientSocket != null)
          clientSocket.close();
      }catch (IOException e) {
        System.err.println("Error while closing a connection.");
      }
    }
      
  }
}

I/O: Jednoduchá serializace

Zdroj: http://java.sun.com/developer/technicalArticles/Programming/serialization/
Serializovatelná třída musí implementovat interface java.io.Serializable, který ovšem neobsahuje žádné metody. V nejjednodušším případě to může vypadat takhle:

import java.io.*;
/* ... */

/* Deklarace serializovatelné třídy, např.: */
public class PersistentTime implements Serializable{ /* ... */ }

/* Zápis: */
PersistentTime     time = new PersistentTime();
FileOutputStream   fos  = null;
ObjectOutputStream out  = null;
try{
  fos = new FileOutputStream("time.ser");
  out = new ObjectOutputStream(fos);
  out.writeObject(time);
  out.close();
}catch(IOException ex){
  ex.printStackTrace();
}

/* Čtení: */
PersistentTime    time = null;
FileInputStream   fis  = null;
ObjectInputStream in   = null;

try{
  fis  = new FileInputStream("time.ser");
  in   = new ObjectInputStream(fis);
  time = (PersistentTime)in.readObject();
  in.close();
}catch(IOException ex){
  ex.printStackTrace();
}catch(ClassNotFoundException ex){
  ex.printStackTrace();
}

Swing: Hello World

Zdroj: http://java.sun.com/docs/books/tutorial/uiswing/start/compile.html

import javax.swing.*;        

public class HelloWorldSwing {
    /**
     * Create the GUI and show it. For thread safety, this method
     * should be invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add the ubiquitous "Hello World" label.
        JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}


Pozn.: Součástí výše uvedených příkladů z webu Sunu je toto upozornění.


 
Na stránce nejsou žádné soubory. [Zobrazit soubory (formulář)]
Na stránce nejsou žádné komentáře. [Zobrazit komentáře (formulář)]