Example usage for java.io PrintWriter PrintWriter

List of usage examples for java.io PrintWriter PrintWriter

Introduction

In this page you can find the example usage for java.io PrintWriter PrintWriter.

Prototype

public PrintWriter(File file) throws FileNotFoundException 

Source Link

Document

Creates a new PrintWriter, without automatic line flushing, with the specified file.

Usage

From source file:flashcrawler.FlashCrawler.java

/**
 * @param args the command line arguments
 *///w  w w.j av  a  2 s .c  om
public static void main(String[] args) throws FileNotFoundException {
    Scanner scn = new Scanner(new File("input.txt"));
    ArrayList<String> ins = new ArrayList();
    while (scn.hasNextLine()) {
        String input = scn.nextLine();
        ins.add(input);
    }

    String URL;
    PrintWriter writer = null;
    writer = new PrintWriter(new FileOutputStream(new File("error-log.txt"), true));

    String File;
    for (String name : ins) {
        File offlinePath = new File("/games/" + name + ".swf");
        String onlinePath = "http://wsh.gamib.com/x/" + name + "/" + name + ".swf";
        System.out.println("Downloading " + onlinePath + " into " + offlinePath);
        URL url = null;
        try {
            System.out.println("...");
            url = new URL(onlinePath);
        } catch (MalformedURLException ex) {
            System.out.println("Failed to create url object");
            writer.println("Error when creating url: " + onlinePath + "\tname");
        }
        try {
            System.out.println("...");
            FileUtils.copyURLToFile(url, offlinePath);
            System.out.println("Success.");
        } catch (IOException ex) {
            System.out.println("Error when downloading game: " + offlinePath);
            writer.println("Error when downloading game: " + offlinePath);
        }

    }
    writer.close();
    System.out.println("Process complete!");
}

From source file:SAXCopy.java

static public void main(String[] arg) {
    String infilename = null;//from w  w w. j a  v  a 2 s. c  o  m
    String outfilename = null;
    if (arg.length == 2) {
        infilename = arg[0];
        outfilename = arg[1];
    } else {
        usage();
    }

    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setErrorHandler(new MyErrorHandler());
        FileOutputStream fos = new FileOutputStream(outfilename);
        PrintWriter out = new PrintWriter(fos);
        MyCopyHandler duper = new MyCopyHandler(out);
        reader.setContentHandler(duper);
        InputSource is = new InputSource(infilename);
        reader.parse(is);
        out.close();
    } catch (SAXException e) {
        System.exit(1);
    } catch (ParserConfigurationException e) {
        System.err.println(e);
        System.exit(1);
    } catch (IOException e) {
        System.err.println(e);
        System.exit(1);
    }
}

From source file:TestDebug_MySQL.java

public static void main(String[] args) {
    Connection conn = null;//from  w ww . j a v  a2  s .c om
    try {
        PrintWriter pw = new PrintWriter(new FileOutputStream("mysql_debug.txt"));
        DriverManager.setLogWriter(pw);
        conn = getConnection();
        String tableName = "myTable";
        System.out.println("tableName=" + tableName);
        System.out.println("conn=" + conn);
        System.out.println("rowCount=" + countRows(conn, tableName));
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.endava.webfundamentals.Main.java

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet httpRequest = new HttpGet("http://petstore.swagger.wordnik.com/api/api-docs");
    HttpResponse httpResponse = httpClient.execute(httpRequest);

    ObjectMapper objectMapper = new ObjectMapper();
    PetStore petStore = objectMapper.readValue(httpResponse.getEntity().getContent(), PetStore.class);

    PrintWriter out = new PrintWriter("PetStore.html");
    out.println("<html>");
    out.println("<header>");
    out.println(petStore.getInfo().getTitle());
    out.println("</header>");
    out.println("<body>");
    out.println("Api Version " + petStore.getApiVersion());
    out.println("Swagger Version " + petStore.getSwaggerVersion());
    out.println("<p>");
    out.println(petStore.getInfo().getDescription());
    out.println("</p>");
    out.println("<p>");
    out.println(petStore.getInfo().getContact());
    out.println("</p>");
    out.println(petStore.getInfo().getLicense());
    out.println(petStore.getInfo().getLicenseUrl());
    out.println("<p>");
    out.println(petStore.getInfo().getTermsOfServiceUrl());
    out.println("</p>");
    out.println("</body>");
    out.println("</html>");

    out.close();//from   w  w  w  . j a va  2  s  . co m
}

From source file:eval.dataset.ParseWikiLog.java

public static void main(String[] ss) throws FileNotFoundException, ParserConfigurationException, IOException {
    FileInputStream fin = new FileInputStream("data/enwiki-20151201-pages-logging.xml.gz");
    GzipCompressorInputStream gzIn = new GzipCompressorInputStream(fin);
    InputStreamReader reader = new InputStreamReader(gzIn);
    BufferedReader br = new BufferedReader(reader);
    PrintWriter pw = new PrintWriter(new FileWriter("data/user_page.txt"));
    pw.println(/*w ww.j  a v a2 s.c o  m*/
            "#list of user names and pages that they have edited, deleted or created. These info are mined from logitems of enwiki-20150304-pages-logging.xml.gz");
    TreeMap<String, Set<String>> userPageList = new TreeMap();
    TreeSet<String> pageList = new TreeSet();
    int counterEntry = 0;
    String currentUser = null;
    String currentPage = null;
    try {
        for (String line = br.readLine(); line != null; line = br.readLine()) {

            if (line.trim().equals("</logitem>")) {
                counterEntry++;
                if (currentUser != null && currentPage != null) {
                    updateMap(userPageList, currentUser, currentPage);
                    pw.println(currentUser + "\t" + currentPage);
                    pageList.add(currentPage);
                }
                currentUser = null;
                currentPage = null;
            } else if (line.trim().startsWith("<username>")) {
                currentUser = line.trim().split(">")[1].split("<")[0].replace(" ", "_");

            } else if (line.trim().startsWith("<logtitle>")) {
                String content = line.trim().split(">")[1].split("<")[0];
                if (content.split(":").length == 1) {
                    currentPage = content.replace(" ", "_");
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(ParseWikiLog.class.getName()).log(Level.SEVERE, null, ex);
    }
    pw.println("#analysed " + counterEntry + " entries of wikipesia log file");
    pw.println("#gathered a list of unique user of size " + userPageList.size());
    pw.println("#gathered a list of pages of size " + pageList.size());
    pw.close();
    gzIn.close();

    PrintWriter pwUser = new PrintWriter(new FileWriter("data/user_list_page_edited.txt"));
    pwUser.println(
            "#list of unique users and pages that they have edited, extracted from logitems of enwiki-20150304-pages-logging.xml.gz");
    for (String user : userPageList.keySet()) {
        pwUser.print(user);
        Set<String> getList = userPageList.get(user);
        for (String page : getList) {
            pwUser.print("\t" + page);
        }
        pwUser.println();
    }
    pwUser.close();

    PrintWriter pwPage = new PrintWriter(new FileWriter("data/all_pages.txt"));
    pwPage.println("#list of the unique pages that are extracted from enwiki-20150304-pages-logging.xml.gz");
    for (String page : pageList) {
        pwPage.println(page);
    }
    pwPage.close();
    System.out.println("#analysed " + counterEntry + " entries of wikipesia log file");
    System.out.println("#gathered a list of unique user of size " + userPageList.size());
    System.out.println("#gathered a list of pages of size " + pageList.size());
}

From source file:SelectingComboSample.java

public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "J", "I" };
    JFrame frame = new JFrame("Selecting JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    JComboBox comboBox = new JComboBox(labels);
    contentPane.add(comboBox, BorderLayout.SOUTH);

    final JTextArea textArea = new JTextArea();
    textArea.setEditable(false);/* w  w  w  .  j a va2 s  .  c  o m*/
    JScrollPane sp = new JScrollPane(textArea);
    contentPane.add(sp, BorderLayout.CENTER);

    ItemListener itemListener = new ItemListener() {
        public void itemStateChanged(ItemEvent itemEvent) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            int state = itemEvent.getStateChange();
            String stateString = ((state == ItemEvent.SELECTED) ? "Selected" : "Deselected");
            pw.print("Item: " + itemEvent.getItem());
            pw.print(", State: " + stateString);
            ItemSelectable is = itemEvent.getItemSelectable();
            pw.print(", Selected: " + selectedString(is));
            pw.println();
            textArea.append(sw.toString());
        }
    };
    comboBox.addItemListener(itemListener);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            pw.print("Command: " + actionEvent.getActionCommand());
            ItemSelectable is = (ItemSelectable) actionEvent.getSource();
            pw.print(", Selected: " + selectedString(is));
            pw.println();
            textArea.append(sw.toString());
        }
    };
    comboBox.addActionListener(actionListener);

    frame.setSize(400, 200);
    frame.setVisible(true);
}

From source file:TextFileTest.java

public static void main(String[] args) {
    Employee[] staff = new Employee[3];

    staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
    staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
    staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

    try {//from   www .j a  va2  s.  com
        // save all employee records to the file employee.dat
        PrintWriter out = new PrintWriter("employee.dat");
        writeData(staff, out);
        out.close();

        // retrieve all records into a new array
        Scanner in = new Scanner(new FileReader("employee.dat"));
        Employee[] newStaff = readData(in);
        in.close();

        // print the newly read employee records
        for (Employee e : newStaff)
            System.out.println(e);
    } catch (IOException exception) {
        exception.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

    String hostName = "hostName";
    String fileName = "fileName";

    SSLSocket sslsock = (SSLSocket) factory.createSocket(hostName, 443);

    SSLSession session = sslsock.getSession();
    X509Certificate cert;/*  ww  w . j a v a2 s  . c  o m*/
    try {
        cert = (X509Certificate) session.getPeerCertificates()[0];
    } catch (SSLPeerUnverifiedException e) {
        System.err.println(session.getPeerHost() + " did not present a valid certificate.");
        return;
    }

    System.out.println(session.getPeerHost() + " has presented a certificate belonging to:");
    Principal p = cert.getSubjectDN();
    System.out.println("\t[" + p.getName() + "]");
    System.out.println("The certificate bears the valid signature of:");
    System.out.println("\t[" + cert.getIssuerDN().getName() + "]");

    System.out.print("Do you trust this certificate (y/n)? ");
    System.out.flush();
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    if (Character.toLowerCase(console.readLine().charAt(0)) != 'y')
        return;

    PrintWriter out = new PrintWriter(sslsock.getOutputStream());

    out.print("GET " + fileName + " HTTP/1.0\r\n\r\n");
    out.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream()));
    String line;
    while ((line = in.readLine()) != null)
        System.out.println(line);

    sslsock.close();
}

From source file:id3Crawler.java

public static void main(String[] args) throws IOException {

    //Input for the directory to be searched.
    System.out.println("Please enter a directory: ");
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();

    //Start a timer to calculate runtime
    startTime = System.currentTimeMillis();

    System.out.println("Starting scan...");

    //Files for output
    PrintWriter pw1 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Song.txt"));
    PrintWriter pw2 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Artist.txt"));
    PrintWriter pw3 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Album.txt"));
    PrintWriter pw4 = new PrintWriter(
            new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/PerformedBy.txt"));
    PrintWriter pw5 = new PrintWriter(
            new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/TrackOf.txt"));
    PrintWriter pw6 = new PrintWriter(
            new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/CreatedBy.txt"));

    //This is used for creating IDs for artists, songs, albums.
    int idCounter = 0;

    //This is used to prevent duplicate artists
    String previousArtist = " ";
    String currentArtist;//from   w  ww  .  ja  v a 2  s . c o  m
    int artistID = 0;

    //This is used to prevent duplicate albums
    String previousAlbum = " ";
    String currentAlbum;
    int albumID = 0;

    //This array holds valid extensions to iterate through
    String[] extensions = new String[] { "mp3" };

    //iterate through all files in a directory
    Iterator<File> it = FileUtils.iterateFiles(new File(input), extensions, true);
    while (it.hasNext()) {

        //open the next file
        File file = it.next();

        //instantiate an mp3file object with the opened file
        MP3 song = GetMP3(file);

        //pass the song through SongInfo and return the required information
        SongInfo info = new SongInfo(song);

        //This is used to prevent duplicate artists/albums
        currentArtist = info.getArtistInfo();
        currentAlbum = info.getAlbumInfo();

        //Append the song information to the end of a text file
        pw1.println(idCounter + "\t" + info.getTitleInfo());

        //This prevents duplicates of artists
        if (!(currentArtist.equals(previousArtist))) {
            pw2.println(idCounter + "\t" + info.getArtistInfo());
            previousArtist = currentArtist;
            artistID = idCounter;
        }

        //This prevents duplicates of albums
        if (!(currentAlbum.equals(previousAlbum))) {
            pw3.println(idCounter + "\t" + info.getAlbumInfo());
            previousAlbum = currentAlbum;
            albumID = idCounter;

            //This formats the IDs for a "CreatedBy" relationship table
            pw6.println(artistID + "\t" + albumID);
        }

        //This formats the IDs for a "PerformedBy" relationship table
        pw4.println(idCounter + "\t" + artistID);

        //This formats the IDs for a "TrackOf" relationship table
        pw5.println(idCounter + "\t" + albumID);

        idCounter++;
        songCounter++;

    }
    scanner.close();
    pw1.close();
    pw2.close();
    pw3.close();
    pw4.close();
    pw5.close();
    pw6.close();

    System.out.println("Scan took " + ((System.currentTimeMillis() - startTime) / 1000.0) + " seconds to scan "
            + songCounter + " items!");

}

From source file:com.idega.util.FileLocalizer.java

public static void main(String[] args) {
    if (args.length != 2) {
        System.err.println("Wimp. I need two parameters, input file og directory and output file");
        System.err.println("Usage java FileLocalizer input output");

        return;/*from   w ww.  j a  v  a2s  .c  o  m*/
    }

    File in = null;
    BufferedWriter out = null;

    Properties props = new Properties();

    try {
        in = new File(args[0]);
    } catch (Exception e) {
        System.err.println("Auli. Error : " + e.toString());

        return;
    }

    try {
        out = new BufferedWriter(new FileWriter(args[1]));
    } catch (java.io.IOException e) {
        System.err.println("Auli. Error : " + e.toString());

        return;
    }

    try {
        findRecursive(in, props);
        props.list(new PrintWriter(out));
    } catch (Exception e) {
        System.err.println("Error reading or writing file : " + e.toString());
    }

    try {
        out.close();
    } catch (java.io.IOException e) {
        System.err.println("Error closing files : " + e.toString());
    }
}