Deprecated: Function set_magic_quotes_runtime() is deprecated in /DISK2/WWW/lokiware.info/mff/wakka.php on line 35
…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é.
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);
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();
}
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í.