Example usage for java.io FileWriter FileWriter

List of usage examples for java.io FileWriter FileWriter

Introduction

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

Prototype

public FileWriter(FileDescriptor fd) 

Source Link

Document

Constructs a FileWriter given a file descriptor, using the platform's java.nio.charset.Charset#defaultCharset() default charset .

Usage

From source file:MainClass.java

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

    ParserGetter kit = new ParserGetter();
    HTMLEditorKit.Parser parser = kit.getParser();

    URL u = new URL("http://www.java2s.com");
    InputStream in = u.openStream();
    InputStreamReader r = new InputStreamReader(in);
    String remoteFileName = u.getFile();
    if (remoteFileName.endsWith("/")) {
        remoteFileName += "index.html";
    }/*from   www .  j a v  a 2 s. c  o m*/
    if (remoteFileName.startsWith("/")) {
        remoteFileName = remoteFileName.substring(1);
    }
    File localDirectory = new File(u.getHost());
    while (remoteFileName.indexOf('/') > -1) {
        String part = remoteFileName.substring(0, remoteFileName.indexOf('/'));
        remoteFileName = remoteFileName.substring(remoteFileName.indexOf('/') + 1);
        localDirectory = new File(localDirectory, part);
    }
    if (localDirectory.mkdirs()) {
        File output = new File(localDirectory, remoteFileName);
        FileWriter out = new FileWriter(output);
        HTMLEditorKit.ParserCallback callback = new PageSaver(out, u);
        parser.parse(r, callback, false);
    }

}

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;/* w  ww  .  j a  v a 2  s  .c om*/
    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:featureExtractor.popularityMeasure.java

public static void main(String[] args) throws IOException {
    //ReadKnownPopularityScores();
    FileWriter fw = new FileWriter(Out_resultFile);
    BufferedWriter bw = new BufferedWriter(fw);

    FileReader inputFile = new FileReader(In_entities);
    BufferedReader bufferReader = new BufferedReader(inputFile);
    String line;//from  w ww .j  a v a  2s  .  c o m
    while ((line = bufferReader.readLine()) != null) {
        String[] row = line.split("\t");
        double score = 0;
        String entityName = row[0].toLowerCase().trim();
        System.out.println("Searching for : " + entityName);
        if (knownScore_table.containsKey(entityName)) {
            //System.out.println("Already known for: " + entityName);
            score = knownScore_table.get(entityName);
        } else {
            System.out.println("Not known for: " + entityName);
            String json = searchTest(entityName, "&scoring=entity");
            try {
                score = ParseJSON_getScore(json);
            } catch (Exception e) {
                score = 0;
            }
            System.out.println("Putting : " + entityName);
            knownScore_table.put(entityName, score);
        }
        bw.write(row[0] + "\t" + score + "\n");
        System.out.println(row[0]);
    }
    bw.close();
}

From source file:cc.redberry.core.performance.StableSort.java

/**
 * @param args the command line arguments
 *//* w w w.  j a v  a 2 s .  com*/
public static void main(String[] args) {
    try {

        //burn JVM
        BitsStreamGenerator bitsStreamGenerator = new Well19937c();

        for (int i = 0; i < 1000; ++i)
            nextArray(1000, bitsStreamGenerator);

        System.out.println("!");
        BufferedWriter timMeanOut = new BufferedWriter(
                new FileWriter("/home/stas/Projects/stableSort/timMean.dat"));
        BufferedWriter insertionMeanOut = new BufferedWriter(
                new FileWriter("/home/stas/Projects/stableSort/insertionMean.dat"));

        BufferedWriter timMaxOut = new BufferedWriter(
                new FileWriter("/home/stas/Projects/stableSort/timMax.dat"));
        BufferedWriter insertionMaxOut = new BufferedWriter(
                new FileWriter("/home/stas/Projects/stableSort/insertionMax.dat"));

        BufferedWriter timSigOut = new BufferedWriter(
                new FileWriter("/home/stas/Projects/stableSort/timSig.dat"));
        BufferedWriter insertionSigOut = new BufferedWriter(
                new FileWriter("/home/stas/Projects/stableSort/insertionSig.dat"));

        DescriptiveStatistics timSort;
        DescriptiveStatistics insertionSort;

        int tryies = 200;
        int arrayLength = 0;
        for (; arrayLength < 1000; ++arrayLength) {

            int[] coSort = nextArray(arrayLength, bitsStreamGenerator);

            timSort = new DescriptiveStatistics();
            insertionSort = new DescriptiveStatistics();
            for (int i = 0; i < tryies; ++i) {
                int[] t1 = nextArray(arrayLength, bitsStreamGenerator);
                int[] t2 = t1.clone();

                long start = System.currentTimeMillis();
                ArraysUtils.timSort(t1, coSort);
                long stop = System.currentTimeMillis();
                timSort.addValue(stop - start);

                start = System.currentTimeMillis();
                ArraysUtils.insertionSort(t2, coSort);
                stop = System.currentTimeMillis();
                insertionSort.addValue(stop - start);
            }
            timMeanOut.write(arrayLength + "\t" + timSort.getMean() + "\n");
            insertionMeanOut.write(arrayLength + "\t" + insertionSort.getMean() + "\n");

            timMaxOut.write(arrayLength + "\t" + timSort.getMax() + "\n");
            insertionMaxOut.write(arrayLength + "\t" + insertionSort.getMax() + "\n");

            timSigOut.write(arrayLength + "\t" + timSort.getStandardDeviation() + "\n");
            insertionSigOut.write(arrayLength + "\t" + insertionSort.getStandardDeviation() + "\n");
        }
        timMeanOut.close();
        insertionMeanOut.close();
        timMaxOut.close();
        insertionMaxOut.close();
        timSigOut.close();
        insertionSigOut.close();
    } catch (IOException ex) {
        Logger.getLogger(StableSort.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:contractEditor.contractHOST4.java

public static void main(String[] args) {

    JSONObject obj = new JSONObject();
    obj.put("name", "HOST4");
    obj.put("context", "VM-deployment");

    //obj.put("Context", new Integer);

    HashMap serviceDescription = new HashMap();
    serviceDescription.put("location", "France");
    serviceDescription.put("certificate", "true");
    serviceDescription.put("volume", "100_GB");
    serviceDescription.put("price", "3_euro");

    obj.put("serviceDescription", serviceDescription);

    HashMap gauranteeTerm = new HashMap();
    gauranteeTerm.put("availability", "more_98_percentage");
    obj.put("gauranteeTerm", gauranteeTerm);

    //Constraint1

    ArrayList creationConstraint1 = new ArrayList();
    ArrayList totalConstraint = new ArrayList();
    totalConstraint.add(creationConstraint1);

    obj.put("creationConstraint", totalConstraint);

    try {/*from   w w  w .j a  v a2s.  c o m*/

        FileWriter file = new FileWriter("confSP" + File.separator + "Host4.json");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);

    /*
            
    JSONParser parser = new JSONParser();
            
    try {
            
    Object obj2 = parser.parse(new FileReader("confSP\\confHost1.json"));
            
    JSONObject jsonObject = (JSONObject) obj2;
            
        HashMap serviceDescription2=(HashMap) jsonObject.get("serviceDescription");
                 
        method.printHashMap(serviceDescription2);
                
                
        HashMap gauranteeTerm2=(HashMap) jsonObject.get("gauranteeTerm");
                 
        method.printHashMap(gauranteeTerm2);
                
                
                
        ArrayList creationConstraint=(ArrayList) jsonObject.get("creationConstraint");
                
        method.printArrayList(creationConstraint);
            
            
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (ParseException e) {
    e.printStackTrace();
    }
            
            
            
            
            
    */

}

From source file:enrichment.Disambiguate.java

/**prerequisites:
 * cd silk_2.5.3/*_links/*from w  w w  .jav  a 2s .co  m*/
 * cat *.nt|sort  -t' ' -k3   > $filename
 * 
 * @param args $filename
 * @throws IOException
 * @throws URISyntaxException
 */
public static void main(String[] args) {
    File file = new File(args[0]);
    if (file.isDirectory()) {
        args = file.list(new OnlyExtFilenameFilter("nt"));
    }

    BufferedReader in;
    for (int q = 0; q < args.length; q++) {
        String filename = null;
        if (file.isDirectory()) {
            filename = file.getPath() + File.separator + args[q];
        } else {
            filename = args[q];
        }
        try {
            FileWriter output = new FileWriter(filename + "_disambiguated.nt");
            String prefix = "@prefix rdrel: <http://rdvocab.info/RDARelationshipsWEMI/> .\n"
                    + "@prefix dbpedia:    <http://de.dbpedia.org/resource/> .\n"
                    + "@prefix frbr:   <http://purl.org/vocab/frbr/core#> .\n"
                    + "@prefix lobid: <http://lobid.org/resource/> .\n"
                    + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
                    + "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n"
                    + "@prefix mo: <http://purl.org/ontology/mo/> .\n"
                    + "@prefix wikipedia: <https://de.wikipedia.org/wiki/> .";
            output.append(prefix + "\n\n");
            in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));

            HashMap<String, HashMap<String, ArrayList<String>>> hm = new HashMap<String, HashMap<String, ArrayList<String>>>();
            String s;
            HashMap<String, ArrayList<String>> hmLobid = new HashMap<String, ArrayList<String>>();
            Stack<String> old_object = new Stack<String>();

            while ((s = in.readLine()) != null) {
                String[] triples = s.split(" ");
                String object = triples[2].substring(1, triples[2].length() - 1);
                if (old_object.size() > 0 && !old_object.firstElement().equals(object)) {
                    hmLobid = new HashMap<String, ArrayList<String>>();
                    old_object = new Stack<String>();
                }
                old_object.push(object);
                String subject = triples[0].substring(1, triples[0].length() - 1);
                System.out.print("\nSubject=" + object);
                System.out.print("\ntriples[2]=" + triples[2]);
                hmLobid.put(subject, getAllCreators(new URI(subject)));
                hm.put(object, hmLobid);

            }
            // get all dbpedia resources
            for (String key_one : hm.keySet()) {
                System.out.print("\n==============\n==== " + key_one + "\n===============");
                int resources_cnt = hm.get(key_one).keySet().size();
                ArrayList<String>[] creators = new ArrayList[resources_cnt];
                HashMap<String, Integer> creators_backed = new HashMap<String, Integer>();
                int x = 0;
                // get all lobid_resources subsumed under the dbpedia resource
                for (String subject_uri : hm.get(key_one).keySet()) {
                    creators[x] = new ArrayList<String>();
                    System.out.print("\n     subject_uri=" + subject_uri);
                    Iterator<String> ite = hm.get(key_one).get(subject_uri).iterator();
                    int y = 0;
                    // get all creators of the lobid resource
                    while (ite.hasNext()) {
                        String creator = ite.next();
                        System.out.print("\n          " + creator);
                        if (creators_backed.containsKey(creator)) {
                            y = creators_backed.get(creator);
                        } else {
                            y = creators_backed.size();
                            creators_backed.put(creator, y);
                        }
                        while (creators[x].size() <= y) {
                            creators[x].add("-");
                        }
                        creators[x].set(y, creator);
                        y++;
                    }
                    x++;
                }
                if (creators_backed.size() == 1) {
                    System.out
                            .println("\n" + "Every resource pointing to " + key_one + " has the same creator!");
                    for (String key_two : hm.get(key_one).keySet()) {
                        output.append("<" + key_two + "> rdrel:workManifested <" + key_one + "> .\n");
                        output.append("<" + key_two + ">  mo:wikipedia <"
                                + key_one.replaceAll("dbpedia\\.org/resource", "wikipedia\\.org/wiki")
                                + "> .\n");
                    }
                } /*else  {
                    for (int a = 0; a < creators.length; a++) {
                       System.out.print(creators[a].toString()+",");
                    }
                  }*/
            }

            output.flush();
            if (output != null) {
                output.close();
            }
        } catch (Exception e) {
            System.out.print("Exception while working on " + filename + ": \n");
            e.printStackTrace(System.out);
        }
    }
}

From source file:fr.inria.zenith.randomWalk.RandomWalkTsG.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//from w  ww  . j  a v a 2 s  .c  o m
 */
public static void main(String[] args) throws IOException, Exception {

    if (args.length < 2) {
        System.err.println("Usage: randomWalkTimeSeriesGenerator <FileName> <TimeSeriesNbr> <TimeSeriesSize>");
        System.exit(1);
    }

    CSVWriter writer = new CSVWriter(new FileWriter(args[0] + "_" + args[1] + "_" + args[2] + ".csv"),
            CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);

    for (int i = 1; i < Integer.parseInt(args[1]) + 2; i++) {
        String[] ts = randomWalk(Integer.parseInt(args[2]) + 1);
        ts[0] = Integer.toString(i);
        writer.writeNext(ts);
        writer.flushQuietly();
    }
    writer.close();
}

From source file:Copy.java

public static void main(String[] args) throws IOException {
    File inputFile = new File("farrago.txt");
    File outputFile = new File("outagain.txt");

    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);
    int c;/*from   w  w  w  .  j  a  v a  2s. c  om*/

    while ((c = in.read()) != -1)
        out.write(c);

    in.close();
    out.close();
}

From source file:CopyCharacters.java

public static void main(String[] args) throws IOException {
    FileReader inputStream = null;
    FileWriter outputStream = null;

    try {//from   w ww. ja v  a 2s .co m
        inputStream = new FileReader("xanadu.txt");
        outputStream = new FileWriter("characteroutput.txt");

        int c;
        while ((c = inputStream.read()) != -1) {
            outputStream.write(c);
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:fm.last.peyote.cacti.PeyoteCactiLauncher.java

public static void main(String[] args) throws JAXBException, IOException {
    if (args.length < 2 || args.length > 3) {
        printUsage();//from  w  w  w  .j  a  v  a2 s.  c  om
    }
    String name = args[0];
    String url = args[1];
    ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/peyote.xml");
    applicationContext.registerShutdownHook();
    try {
        InputData inputData = createInputData(args, applicationContext, name, url);
        PeyoteMarshaller marshaller = applicationContext.getBean(PeyoteMarshaller.class);
        marshaller.setInputData(inputData);
        log.info("Starting Peyote");
        File file = new File("datatemplate.xml");
        Writer outWriter = new FileWriter(file);
        marshaller.generateCactiDataTemplate(outWriter);
        outWriter.close();
        log.info("generated data template for '" + name + "' in " + file.getAbsolutePath());

        // file = new File("graphtemplate.xml");
        // outWriter = new FileWriter(file);
        // marshaller.generateCactiGraphTemplate(outWriter);
        // outWriter.close();
        // log.info("generated data template for '" + name + "' in " +
        // file.getAbsolutePath());

        log.info("Peyote finished.");
    } finally {
        applicationContext.close();
    }
}