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);
Standardní vstup je posílán serveru, a odpovědi serveru posílány na standardní výstup.
Zdroj: http://java.sun.com/docs/books/tutorial/networking/sockets/readingWriting.html
import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) throws IOException { static final HOST = "localhost"; static final PORTNO = 12345; Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket(HOST, PORTNO); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream() )); } catch (UnknownHostException e) { System.err.println("Don't know about host"); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } }
Inspirováno tímto příkladem. Opakuje vstup od klienta po řádcích. Umí obsloužit více spojení.
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."); } } } }
import java.net.*; import java.io.*; public class UplneBlbyServer { public static void main(String[] args) throws IOException { ServerSocket s = new ServerSocket(12345); try { Socket socket = s.accept(); try { BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream() )); PrintWriter out = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ), true /* autoFlush */); String s = null; while( (s = in.readLine()) != null ) out.println(str); } finally { socket.close(); } } finally { s.close(); } } }
Zdroj: http://java.sun.com/docs/books/tutorial/networking/urls/index.html
Nejjednodušší čtení URL:
import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream()) ); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } }
Složitější čtení pomocí URLConnection (můžeme zapisovat, číst hlavičky):
import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yc = yahoo.openConnection(); // (!) URLConnection /* tady můžeme udělat třeba tohle: * con.connect(); * System.out.println("Content-Type: "+con.getContentType()); * System.out.println("Content-Length: "+con.getContentLength()); */ BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } }
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í.