List of usage examples for java.io PrintWriter PrintWriter
public PrintWriter(File file) throws FileNotFoundException
From source file:com.congiu.load.csv.Main.java
public static void main(String[] args) { Options opts = buildCommandLineOptions(); Configuration conf = new Configuration(); try {//w w w. j a v a 2 s . c om CommandLine cmd = processArguments(opts, args); if (cmd.hasOption(OPT_HELP[0])) { printUsage(opts, new PrintWriter(System.out)); System.exit(0); } // all unprocessed arguments are files. // let's first check if they all exist for (String s : cmd.getArgs()) { if (!FSUtils.fileExists(conf, s)) { throw new Exception("File " + s + " does not exist."); } } CSVConverter converter = getCSVConverter(cmd); for (String s : cmd.getArgs()) { } } catch (Exception ex) { System.err.println("There was a problem parsing your arguments."); System.err.println(ex); printUsage(opts, new PrintWriter(System.err)); System.exit(-1); } }
From source file:Connect.java
public static void main(String[] args) { try { // Handle exceptions below // Get our command-line arguments String hostname = args[0]; int port = Integer.parseInt(args[1]); String message = ""; if (args.length > 2) for (int i = 2; i < args.length; i++) message += args[i] + " "; // Create a Socket connected to the specified host and port. Socket s = new Socket(hostname, port); // Get the socket output stream and wrap a PrintWriter around it PrintWriter out = new PrintWriter(s.getOutputStream()); // Sent the specified message through the socket to the server. out.print(message + "\r\n"); out.flush(); // Send it now. // Get an input stream from the socket and wrap a BufferedReader // around it, so we can read lines of text from the server. BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); // Before we start reading the server's response tell the socket // that we don't want to wait more than 3 seconds s.setSoTimeout(3000);//from ww w . j a v a 2 s.com // Now read lines from the server until the server closes the // connection (and we get a null return indicating EOF) or until // the server is silent for 3 seconds. try { String line; while ((line = in.readLine()) != null) // If we get a line System.out.println(line); // print it out. } catch (SocketTimeoutException e) { // We end up here if readLine() times out. System.err.println("Timeout; no response from server."); } out.close(); // Close the output stream in.close(); // Close the input stream s.close(); // Close the socket } catch (IOException e) { // Handle IO and network exceptions here System.err.println(e); } catch (NumberFormatException e) { // Bad port number System.err.println("You must specify the port as a number"); } catch (ArrayIndexOutOfBoundsException e) { // wrong # of args System.err.println("Usage: Connect <hostname> <port> message..."); } }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getMySqlConnection(); // Set up the environment for creating the initial context Hashtable env = new Hashtable(11); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); env.put(Context.PROVIDER_URL, "file:/jdbc"); Context context = new InitialContext(env); NamingEnumeration list = context.list("jdbc"); while (list.hasMore()) { NameClassPair nc = (NameClassPair) list.next(); System.out.println(nc);/*from ww w . j a v a 2 s . c o m*/ } OracleDataSource ods = new OracleDataSource(); ods.setDriverType("thin"); ods.setServerName("localhost"); ods.setNetworkProtocol("tcp"); ods.setDatabaseName("databaseName"); ods.setPortNumber(1521); ods.setUser("userName"); ods.setPassword("Password"); Context ctx = new InitialContext(); ctx.bind("file:/jdbc/mydb", ods); // Get the initial context of JNDI and lookup the datasource. InitialContext ic = new InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource) ic.lookup("file:/jdbc/mydb"); // Set the optional printwriter where the trace log is to be directed. ds.setLogWriter(new PrintWriter(new FileOutputStream("c:/datasource.log"))); Connection con1 = ds.getConnection(); Connection con2 = ds.getConnection("userName", "password"); conn.close(); }
From source file:GenericClient.java
public static void main(String[] args) throws IOException { try {/*from www. jav a 2s .com*/ // Check the number of arguments if (args.length != 2) throw new IllegalArgumentException("Wrong number of args"); // Parse the host and port specifications String host = args[0]; int port = Integer.parseInt(args[1]); // Connect to the specified host and port Socket s = new Socket(host, port); // Set up streams for reading from and writing to the server. // The from_server stream is final for use in the inner class below final Reader from_server = new InputStreamReader(s.getInputStream()); PrintWriter to_server = new PrintWriter(s.getOutputStream()); // Set up streams for reading from and writing to the console // The to_user stream is final for use in the anonymous class below BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in)); // Pass true for auto-flush on println() final PrintWriter to_user = new PrintWriter(System.out, true); // Tell the user that we've connected to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort()); // Create a thread that gets output from the server and displays // it to the user. We use a separate thread for this so that we // can receive asynchronous output Thread t = new Thread() { public void run() { char[] buffer = new char[1024]; int chars_read; try { // Read characters from the server until the // stream closes, and write them to the console while ((chars_read = from_server.read(buffer)) != -1) { to_user.write(buffer, 0, chars_read); to_user.flush(); } } catch (IOException e) { to_user.println(e); } // When the server closes the connection, the loop above // will end. Tell the user what happened, and call // System.exit(), causing the main thread to exit along // with this one. to_user.println("Connection closed by server."); System.exit(0); } }; // Now start the server-to-user thread t.start(); // In parallel, read the user's input and pass it on to the server. String line; while ((line = from_user.readLine()) != null) { to_server.print(line + "\r\n"); to_server.flush(); } // If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end // their input, we'll get an EOF, and the loop above will exit. // When this happens, we stop the server-to-user thread and close // the socket. s.close(); to_user.println("Connection closed by client."); System.exit(0); } // If anything goes wrong, print an error message catch (Exception e) { System.err.println(e); System.err.println("Usage: java GenericClient <hostname> <port>"); } }
From source file:examples.nntp.MessageThreading.java
public static void main(String[] args) throws SocketException, IOException { if (args.length != 2 && args.length != 4) { System.out.println("Usage: MessageThreading <hostname> <groupname> [<user> <password>]"); return;/*from w w w .j a va 2 s . com*/ } String hostname = args[0]; String newsgroup = args[1]; NNTPClient client = new NNTPClient(); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); client.connect(hostname); if (args.length == 4) { // Optional auth String user = args[2]; String password = args[3]; if (!client.authenticate(user, password)) { System.out.println("Authentication failed for user " + user + "!"); System.exit(1); } } String fmt[] = client.listOverviewFmt(); if (fmt != null) { System.out.println("LIST OVERVIEW.FMT:"); for (String s : fmt) { System.out.println(s); } } else { System.out.println("Failed to get OVERVIEW.FMT"); } NewsgroupInfo group = new NewsgroupInfo(); client.selectNewsgroup(newsgroup, group); long lowArticleNumber = group.getFirstArticleLong(); long highArticleNumber = lowArticleNumber + 5000; System.out .println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]"); Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber); System.out.println("Building message thread tree..."); Threader threader = new Threader(); Article root = (Article) threader.thread(articles); Article.printThread(root, 0); }
From source file:ch.epfl.lsir.xin.test.GlobalMeanTest.java
/** * @param args//from ww w .ja va 2 s . com */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub PrintWriter logger = new PrintWriter(".//results//GlobalMean"); PropertiesConfiguration config = new PropertiesConfiguration(); config.setFile(new File("conf//GlobalMean.properties")); try { config.load(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Read rating data..."); DataLoaderFile loader = new DataLoaderFile(".//data//MoveLens100k.txt"); loader.readSimple(); DataSetNumeric dataset = loader.getDataset(); System.out.println("Number of ratings: " + dataset.getRatings().size() + " Number of users: " + dataset.getUserIDs().size() + " Number of items: " + dataset.getItemIDs().size()); logger.println("Number of ratings: " + dataset.getRatings().size() + ", Number of users: " + dataset.getUserIDs().size() + ", Number of items: " + dataset.getItemIDs().size()); double totalMAE = 0; double totalRMSE = 0; int F = 5; logger.println(F + "- folder cross validation."); logger.flush(); ArrayList<ArrayList<NumericRating>> folders = new ArrayList<ArrayList<NumericRating>>(); for (int i = 0; i < F; i++) { folders.add(new ArrayList<NumericRating>()); } while (dataset.getRatings().size() > 0) { int index = new Random().nextInt(dataset.getRatings().size()); int r = new Random().nextInt(F); folders.get(r).add(dataset.getRatings().get(index)); dataset.getRatings().remove(index); } for (int folder = 1; folder <= F; folder++) { System.out.println("Folder: " + folder); logger.println("Folder: " + folder); ArrayList<NumericRating> trainRatings = new ArrayList<NumericRating>(); ArrayList<NumericRating> testRatings = new ArrayList<NumericRating>(); for (int i = 0; i < folders.size(); i++) { if (i == folder - 1)//test data { testRatings.addAll(folders.get(i)); } else {//training data trainRatings.addAll(folders.get(i)); } } //create rating matrix HashMap<String, Integer> userIDIndexMapping = new HashMap<String, Integer>(); HashMap<String, Integer> itemIDIndexMapping = new HashMap<String, Integer>(); for (int i = 0; i < dataset.getUserIDs().size(); i++) { userIDIndexMapping.put(dataset.getUserIDs().get(i), i); } for (int i = 0; i < dataset.getItemIDs().size(); i++) { itemIDIndexMapping.put(dataset.getItemIDs().get(i), i); } RatingMatrix trainRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < trainRatings.size(); i++) { trainRatingMatrix.set(userIDIndexMapping.get(trainRatings.get(i).getUserID()), itemIDIndexMapping.get(trainRatings.get(i).getItemID()), trainRatings.get(i).getValue()); } RatingMatrix testRatingMatrix = new RatingMatrix(dataset.getUserIDs().size(), dataset.getItemIDs().size()); for (int i = 0; i < testRatings.size(); i++) { testRatingMatrix.set(userIDIndexMapping.get(testRatings.get(i).getUserID()), itemIDIndexMapping.get(testRatings.get(i).getItemID()), testRatings.get(i).getValue()); } System.out.println("Training: " + trainRatingMatrix.getTotalRatingNumber() + " vs Test: " + testRatingMatrix.getTotalRatingNumber()); logger.println("Initialize a recommendation model based on global average method."); GlobalAverage algo = new GlobalAverage(trainRatingMatrix); algo.setLogger(logger); algo.build(); algo.saveModel(".//localModels//" + config.getString("NAME")); logger.println("Save the model."); logger.flush(); System.out.println(trainRatings.size() + " vs. " + testRatings.size()); double RMSE = 0; double MAE = 0; int count = 0; for (int i = 0; i < testRatings.size(); i++) { NumericRating rating = testRatings.get(i); double prediction = algo.predict(rating.getUserID(), rating.getItemID()); if (Double.isNaN(prediction)) { System.out.println("no prediction"); continue; } MAE = MAE + Math.abs(rating.getValue() - prediction); RMSE = RMSE + Math.pow((rating.getValue() - prediction), 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); // System.out.println("MAE: " + MAE + " RMSE: " + RMSE); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " MAE: " + MAE + " RMSE: " + RMSE); logger.flush(); totalMAE = totalMAE + MAE; totalRMSE = totalRMSE + RMSE; } System.out.println("MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Final results: MAE: " + totalMAE / F + " RMSE: " + totalRMSE / F); logger.flush(); logger.close(); //MAE: 0.9338607074893257 RMSE: 1.1170971131112037 (MovieLens1M) //MAE: 0.9446876509332618 RMSE: 1.1256517870920375 (MovieLens100K) }
From source file:HttpMirror.java
public static void main(String args[]) { try {/*from w ww . ja v a 2 s .co m*/ // Get the port to listen on int port = Integer.parseInt(args[0]); // Create a ServerSocket to listen on that port. ServerSocket ss = new ServerSocket(port); // Now enter an infinite loop, waiting for & handling connections. for (;;) { // Wait for a client to connect. The method will block; // when it returns the socket will be connected to the client Socket client = ss.accept(); // Get input and output streams to talk to the client BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); // Start sending our reply, using the HTTP 1.1 protocol out.print("HTTP/1.1 200 \r\n"); // Version & status code out.print("Content-Type: text/plain\r\n"); // The type of data out.print("Connection: close\r\n"); // Will close stream out.print("\r\n"); // End of headers // Now, read the HTTP request from the client, and send it // right back to the client as part of the body of our // response. The client doesn't disconnect, so we never get // an EOF. It does sends an empty line at the end of the // headers, though. So when we see the empty line, we stop // reading. This means we don't mirror the contents of POST // requests, for example. Note that the readLine() method // works with Unix, Windows, and Mac line terminators. String line; while ((line = in.readLine()) != null) { if (line.length() == 0) break; out.print(line + "\r\n"); } // Close socket, breaking the connection to the client, and // closing the input and output streams out.close(); // Flush and close the output stream in.close(); // Close the input stream client.close(); // Close the socket itself } // Now loop again, waiting for the next connection } // If anything goes wrong, print an error message catch (Exception e) { System.err.println(e); System.err.println("Usage: java HttpMirror <port>"); } }
From source file:clientetcp.ClienteTCP.java
public static void main(String[] args) { try {/*ww w .ja v a 2 s. co m*/ SSLClient client = new SSLClient(); SSLSocket s = (SSLSocket) client.createSocket("localhost", 7443); PrintWriter writer = new PrintWriter(s.getOutputStream()); InputStream reader = s.getInputStream(); writer.println("Hola"); } catch (Exception exception) { } }
From source file:HDFSFileFinder.java
public static void main(String[] args) { try {/* ww w .j a va 2s. c o m*/ writer = new PrintWriter(System.out); parseCommandLineOptions(args); } catch (ParseException e) { System.out.println("There was an exception processing the supplied options"); printUsage(writer); e.printStackTrace(); System.exit(0); } getBlockLocationsFromHdfs(); }
From source file:com.logic.test.FTPSLogic.java
public static void main(String[] args) { String serverAdress = "62.2.176.167"; String username = "RLSFTPRead"; String password = "ftp4rls"; int port = 990; FTPSClient ftpsClient = new FTPSClient("TLS", true); String remoteFile = "REM - Persons Extract.csv"; File localFile = new File("Persons Extract.csv"); try {//from w w w.jav a2 s .com TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); //ftpsClient.setTrustManager(trustManager[0]); //KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); //kmf.init(null, null); //KeyManager km = kmf.getKeyManagers()[0]; //ftpsClient.setKeyManager(km); ftpsClient.setBufferSize(1024 * 1024); ftpsClient.setConnectTimeout(100000); ftpsClient.connect(InetAddress.getByName(serverAdress), port); ftpsClient.setSoTimeout(100000); if (ftpsClient.login(username, password)) { ftpsClient.execPBSZ(0); ftpsClient.execPROT("P"); ftpsClient.changeWorkingDirectory("/"); ftpsClient.setFileType(FTP.BINARY_FILE_TYPE); ftpsClient.enterLocalPassiveMode(); //ftpsClient.retrieveFile(remoteFile, new FileOutputStream(localFile)); for (FTPFile file : ftpsClient.listFiles()) { System.out.println("Nom " + file.getName()); } } } catch (SocketException e) { ; } catch (UnknownHostException e) { ; } catch (IOException e) { ; } catch (Exception e) { ; } finally { try { ftpsClient.logout(); } catch (Exception e2) { } try { ftpsClient.disconnect(); } catch (Exception e2) { } } }