List of usage examples for java.io ObjectInputStream close
public void close() throws IOException
From source file:ObjectReader.java
public static void main(String[] arguments) { try {//from www .j a v a 2 s .co m FileInputStream fi = new FileInputStream("message.obj"); ObjectInputStream oi = new ObjectInputStream(fi); Message mess = (Message) oi.readObject(); System.out.println("Message:\n"); System.out.println("From: " + mess.from); System.out.println("To: " + mess.to); System.out.println("Date: " + mess.when + "\n"); for (int i = 0; i < mess.lineCount; i++) System.out.println(mess.text[i]); oi.close(); } catch (Exception e) { System.out.println("Error " + e.toString()); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { Junk obj1 = new Junk("A"); Junk obj2 = new Junk("B"); Junk obj3 = new Junk("V"); ObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream("C:/JunkObjects.bin"))); objectOut.writeObject(obj1); // Write object objectOut.writeObject(obj2); // Write object objectOut.writeObject(obj3); // Write object objectOut.close(); // Close the output stream ObjectInputStream objectIn = null; int objectCount = 0; Junk object = null;/*w w w . j a va2 s . c om*/ objectIn = new ObjectInputStream(new BufferedInputStream(new FileInputStream("C:/JunkObjects.bin"))); // Read from the stream until we hit the end while (objectCount < 3) { object = (Junk) objectIn.readObject(); objectCount++; System.out.println(object); } objectIn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream("file.data"))); out.writeObject(Calendar.getInstance()); out.writeObject(new BigDecimal("123.123")); out.writeInt(1);/* ww w . ja va 2 s . c o m*/ out.writeUTF("tutorial"); out.close(); ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("file.data"))); BigDecimal price; int unit; String desc; Calendar date = (Calendar) in.readObject(); System.out.println(date); price = (BigDecimal) in.readObject(); unit = in.readInt(); desc = in.readUTF(); System.out.println(unit); System.out.println(desc); System.out.println(price); in.close(); }
From source file:Data.java
public static void main(String[] args) { Data data = new Data(1); try {//from w w w . ja v a 2 s . co m ObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream("C:/test.bin"))); objectOut.writeObject(data); System.out.println("1st Object written has value: " + data.getValue()); data.setValue(2); objectOut.writeObject(data); System.out.println("2nd Object written has value: " + data.getValue()); data.setValue(3); objectOut.writeObject(data); System.out.println("3rd Object written has value: " + data.getValue()); objectOut.close(); } catch (IOException e) { e.printStackTrace(System.err); } try { ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream(new FileInputStream("C:/test.bin"))); Data data1 = (Data) objectIn.readObject(); Data data2 = (Data) objectIn.readObject(); Data data3 = (Data) objectIn.readObject(); System.out.println(data1.equals(data2)); System.out.println(data2.equals(data3)); System.out.println(data1.getValue()); System.out.println(data2.getValue()); System.out.println(data3.getValue()); objectIn.close(); } catch (Exception e) { e.printStackTrace(System.err); } }
From source file:DataIOTest2.java
public static void main(String[] args) throws IOException { // write the data out ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("invoice1.txt")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; for (int i = 0; i < prices.length; i++) { out.writeDouble(prices[i]);/*from ww w . j av a2 s . co m*/ out.writeChar('\t'); out.writeInt(units[i]); out.writeChar('\t'); out.writeChars(descs[i]); out.writeChar('\n'); } out.close(); // read it in again ObjectInputStream in = new ObjectInputStream(new FileInputStream("invoice1.txt")); double price; int unit; String desc; double total = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab desc = in.readLine(); System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); }
From source file:com.frostvoid.trekwar.server.TrekwarServer.java
public static void main(String[] args) { // load language try {//from w w w . j a v a 2 s.c om lang = new Language(Language.ENGLISH); } catch (IOException ioe) { System.err.println("FATAL ERROR: Unable to load language file!"); System.exit(1); } System.out.println(lang.get("trekwar_server") + " " + VERSION); System.out.println("==============================================".substring(0, lang.get("trekwar_server").length() + 1 + VERSION.length())); // Handle parameters Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg() .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load"); options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg() .withDescription("the port number to bind to (default 8472)").create("p")); options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg() .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s")); options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg() .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF") .create("l")); options.addOption("h", "help", false, "prints this help message"); CommandLineParser cliParser = new BasicParser(); try { CommandLine cmd = cliParser.parse(options, args); String portStr = cmd.getOptionValue("p"); String galaxyFileStr = cmd.getOptionValue("g"); String saveIntervalStr = cmd.getOptionValue("s"); String logLevelStr = cmd.getOptionValue("l"); if (cmd.hasOption("h")) { HelpFormatter help = new HelpFormatter(); help.printHelp("TrekwarServer", options); System.exit(0); } if (cmd.hasOption("g") && galaxyFileStr != null) { galaxyFileName = galaxyFileStr; } else { throw new ParseException("galaxy file not specified"); } if (cmd.hasOption("p") && portStr != null) { port = Integer.parseInt(portStr); if (port < 1 || port > 65535) { throw new NumberFormatException(lang.get("port_number_out_of_range")); } } else { port = 8472; } if (cmd.hasOption("s") && saveIntervalStr != null) { saveInterval = Integer.parseInt(saveIntervalStr); if (saveInterval < 1 || saveInterval > 100) { throw new NumberFormatException("Save Interval out of range (1-100)"); } } else { saveInterval = 5; } if (cmd.hasOption("l") && logLevelStr != null) { if (logLevelStr.equalsIgnoreCase("finest")) { LOG.setLevel(Level.FINEST); } else if (logLevelStr.equalsIgnoreCase("finer")) { LOG.setLevel(Level.FINER); } else if (logLevelStr.equalsIgnoreCase("fine")) { LOG.setLevel(Level.FINE); } else if (logLevelStr.equalsIgnoreCase("config")) { LOG.setLevel(Level.CONFIG); } else if (logLevelStr.equalsIgnoreCase("info")) { LOG.setLevel(Level.INFO); } else if (logLevelStr.equalsIgnoreCase("warning")) { LOG.setLevel(Level.WARNING); } else if (logLevelStr.equalsIgnoreCase("severe")) { LOG.setLevel(Level.SEVERE); } else if (logLevelStr.equalsIgnoreCase("off")) { LOG.setLevel(Level.OFF); } else if (logLevelStr.equalsIgnoreCase("all")) { LOG.setLevel(Level.ALL); } else { System.err.println("ERROR: invalid log level: " + logLevelStr); System.err.println("Run again with -h flag to see valid log level values"); System.exit(1); } } else { LOG.setLevel(Level.INFO); } // INIT LOGGING try { LOG.setUseParentHandlers(false); initLogging(); } catch (IOException ex) { System.err.println("Unable to initialize logging to file"); System.err.println(ex); System.exit(1); } } catch (Exception ex) { System.err.println("ERROR: " + ex.getMessage()); System.err.println("use -h for help"); System.exit(1); } LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up"); // LOAD GALAXY File galaxyFile = new File(galaxyFileName); if (galaxyFile.exists()) { try { long timer = System.currentTimeMillis(); LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile)); galaxy = (Galaxy) ois.readObject(); timer = System.currentTimeMillis() - timer; LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer); ois.close(); } catch (IOException ioe) { LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe); } catch (ClassNotFoundException cnfe) { LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe); } } else { System.err.println("Error: file " + galaxyFileName + " not found"); System.exit(1); } // if turn == 0 (start of game), execute first turn to update fog of war. if (galaxy.getCurrentTurn() == 0) { TurnExecutor.executeTurn(galaxy); } LOG.log(Level.INFO, "Current turn : {0}", galaxy.getCurrentTurn()); LOG.log(Level.INFO, "Turn speed : {0} seconds", galaxy.getTurnSpeed() / 1000); LOG.log(Level.INFO, "Save Interval : {0}", saveInterval); LOG.log(Level.INFO, "Users / max : {0} / {1}", new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() }); // START SERVER try { server = new ServerSocket(port); LOG.log(Level.INFO, "Server listening on port {0}", port); } catch (BindException be) { LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port); System.err.println(be); System.exit(1); } catch (IOException ioe) { LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port); System.err.println(ioe); System.exit(1); } galaxy.startup(); Thread timerThread = new Thread(new Runnable() { @Override @SuppressWarnings("SleepWhileInLoop") public void run() { while (true) { try { Thread.sleep(1000); // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING) if (System.currentTimeMillis() > galaxy.nextTurnDate) { StringBuffer loggedInUsers = new StringBuffer(); for (User u : galaxy.getLoggedInUsers()) { loggedInUsers.append(u.getUsername()).append(", "); } long time = TurnExecutor.executeTurn(galaxy); LOG.log(Level.INFO, "Turn {0} executed in {1} ms", new Object[] { galaxy.getCurrentTurn(), time }); LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString()); LOG.log(Level.INFO, "===================================================================================="); if (galaxy.getCurrentTurn() % saveInterval == 0) { saveGalaxy(); } galaxy.lastTurnDate = System.currentTimeMillis(); galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed; } } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e); } } } }); timerThread.start(); // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS while (true) { Socket clientConnection; try { clientConnection = server.accept(); ClientSession c = new ClientSession(clientConnection, galaxy); Thread t = new Thread(c); t.start(); } catch (IOException ex) { LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex); } } }
From source file:com.couragelabs.logging.LogAppenderTestFixture.java
/** * Use this method to test the appender. Run this first, then run * GlobalContextSocketAppender::main/*from www. jav a2 s . co m*/ * * @param args Program arguments. None are needed. * @throws java.lang.Exception if things go wrong */ @SuppressWarnings("InfiniteLoopStatement") public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(PORT); System.out.println("Starting listen loop."); while (true) { try { final Socket clientSocket = serverSocket.accept(); System.out.println("Received client connection."); new Thread() { @Override public void run() { ObjectInputStream i = null; try { i = new ObjectInputStream(clientSocket.getInputStream()); while (true) { Object received = i.readObject(); System.out.println(ToStringBuilder.reflectionToString(received, ToStringStyle.SHORT_PREFIX_STYLE)); Thread.sleep(1000); } } catch (EOFException e) { System.out.println("Client closed connection."); } catch (Throwable t) { t.printStackTrace(); } finally { if (i != null) { try { i.close(); } catch (Throwable t) { t.printStackTrace(); } } } } }.start(); Thread.sleep(1000); } catch (Throwable t) { t.printStackTrace(); } System.out.println("Next..."); } }
From source file:ObjectStreams.java
public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectOutputStream out = null; try {//from w w w . j a v a 2 s .c o m out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile))); out.writeObject(Calendar.getInstance()); for (int i = 0; i < prices.length; i++) { out.writeObject(prices[i]); out.writeInt(units[i]); out.writeUTF(descs[i]); } } finally { out.close(); } ObjectInputStream in = null; try { in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dataFile))); Calendar date = null; BigDecimal price; int unit; String desc; BigDecimal total = new BigDecimal(0); date = (Calendar) in.readObject(); System.out.format("On %tA, %<tB %<te, %<tY:%n", date); try { while (true) { price = (BigDecimal) in.readObject(); unit = in.readInt(); desc = in.readUTF(); System.out.format("You ordered %d units of %s at $%.2f%n", unit, desc, price); total = total.add(price.multiply(new BigDecimal(unit))); } } catch (EOFException e) { } System.out.format("For a TOTAL of: $%.2f%n", total); } finally { in.close(); } }
From source file:ComplexCompany.java
public static void main(String args[]) throws Exception { Socket socket1;// ww w .j a v a 2s. c o m int portNumber = 1777; String str = ""; socket1 = new Socket(InetAddress.getLocalHost(), portNumber); ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream()); ComplexCompany comp = new ComplexCompany("A"); ComplexEmployee emp0 = new ComplexEmployee("B", 1000); comp.addPresident(emp0); ComplexDepartment sales = new ComplexDepartment("C"); ComplexEmployee emp1 = new ComplexEmployee("D", 1200); sales.addManager(emp1); comp.addDepartment(sales); ComplexDepartment accounting = new ComplexDepartment("E"); ComplexEmployee emp2 = new ComplexEmployee("F", 1230); accounting.addManager(emp2); comp.addDepartment(accounting); ComplexDepartment maintenance = new ComplexDepartment("Maintenance"); ComplexEmployee emp3 = new ComplexEmployee("Greg Hladlick", 1020); maintenance.addManager(emp3); comp.addDepartment(maintenance); oos.writeObject(comp); while ((str = (String) ois.readObject()) != null) { System.out.println(str); oos.writeObject("bye"); if (str.equals("bye")) break; } ois.close(); oos.close(); socket1.close(); }
From source file:net.lightbody.bmp.proxy.jetty.http.HttpServer.java
/** Construct server from command line arguments. * @param args /*from www. ja va2 s . com*/ */ public static void main(String[] args) { if (args.length == 0 || args.length > 2) { System.err.println("\nUsage - java net.lightbody.bmp.proxy.jetty.http.HttpServer [<addr>:]<port>"); System.err.println("\nUsage - java net.lightbody.bmp.proxy.jetty.http.HttpServer -r [savefile]"); System.err.println(" Serves files from '.' directory"); System.err.println(" Dump handler for not found requests"); System.err.println(" Default port is 8080"); System.exit(1); } try { if (args.length == 1) { // Create the server HttpServer server = new HttpServer(); // Default is no virtual host String host = null; HttpContext context = server.getContext(host, "/"); context.setResourceBase("."); context.addHandler(new ResourceHandler()); context.addHandler(new DumpHandler()); context.addHandler(new NotFoundHandler()); InetAddrPort address = new InetAddrPort(args[0]); server.addListener(address); server.start(); } else { Resource resource = Resource.newResource(args[1]); ObjectInputStream in = new ObjectInputStream(resource.getInputStream()); HttpServer server = (HttpServer) in.readObject(); in.close(); server.start(); } } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } }