Example usage for java.io BufferedWriter close

List of usage examples for java.io BufferedWriter close

Introduction

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

Prototype

@SuppressWarnings("try")
    public void close() throws IOException 

Source Link

Usage

From source file:adalid.commons.velocity.VelocityEngineer.java

public static void write(VelocityContext context, String tempname, String filename, String charset1,
        String charset2) throws Exception {
    charset1 = StringUtils.defaultIfBlank(charset1, getTemplateEncoding(tempname));
    charset2 = StringUtils.defaultIfBlank(charset2, getDocumentEncoding(filename));
    //      if (!charset1.equals(VELOCITY_TEMPLATE_DEFAULT_ENCODING)) {
    //          log(Level.INFO, "write", "template=" + tempname, "template-encoding=" + charset1, "document-encoding=" + charset2);
    //      }/*from ww w. j  a  v a2 s.c  o m*/
    //      if (!charset1.equals(charset2)) {
    //          log(Level.WARN, "write", "template=" + tempname, "template-encoding=" + charset1, "document-encoding=" + charset2);
    //      }
    StringWriter sw = merge(context, tempname, charset1);
    if (sw != null) {
        FileOutputStream fileOutputStream;
        OutputStreamWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileOutputStream = new FileOutputStream(filename);
            fileWriter = new OutputStreamWriter(fileOutputStream, charset2);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(sw.toString());
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException ex) {
                    logger.fatal(ThrowableUtils.getString(ex), ex);
                }
            }
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException ex) {
                    logger.fatal(ThrowableUtils.getString(ex), ex);
                }
            }
        }
    }
}

From source file:com.microsoft.azure.management.compute.samples.DeployImageFromContainerRegistryToKubernetes.java

/**
 * Main function which runs the actual sample.
 *
 * @param azure instance of the azure client
 * @param clientId secondary service principal client ID
 * @param secret secondary service principal secret
 * @return true if sample runs successfully
 */// w  w  w  .jav a 2s. c o  m
public static boolean runSample(Azure azure, String clientId, String secret) {
    final String rgName = SdkContext.randomResourceName("rgACR", 15);
    final String acrName = SdkContext.randomResourceName("acrsample", 20);
    final String saName = SdkContext.randomResourceName("sa", 20);
    final String acsName = SdkContext.randomResourceName("acssample", 30);
    final String rootUserName = "acsuser";
    final Region region = Region.US_EAST;
    final String dockerImageName = "nginx";
    final String dockerImageTag = "latest";
    final String dockerContainerName = "acrsample-nginx";
    String acsSecretName = "mysecret112233";
    String acsNamespace = "acrsample";
    String acsLbIngressName = "lb-acrsample";
    String servicePrincipalClientId = clientId; // replace with a real service principal client id
    String servicePrincipalSecret = secret; // and corresponding secret
    SSHShell shell = null;

    try {

        //=============================================================
        // If service principal client id and secret are not set via the local variables, attempt to read the service
        //   principal client id and secret from a secondary ".azureauth" file set through an environment variable.
        //
        //   If the environment variable was not set then reuse the main service principal set for running this sample.

        if (servicePrincipalClientId.isEmpty() || servicePrincipalSecret.isEmpty()) {
            String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2");

            if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty()
                    || !Files.exists(Paths.get(envSecondaryServicePrincipal))) {
                envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION");
            }

            servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal);
            servicePrincipalSecret = Utils.getSecondaryServicePrincipalSecret(envSecondaryServicePrincipal);
        }

        //=============================================================
        // Create an SSH private/public key pair to be used when creating the container service

        System.out.println("Creating an SSH private and public key pair");

        SSHShell.SshPublicPrivateKey sshKeys = SSHShell.generateSSHKeys("", "ACS");
        System.out.println("SSH private key value: \n" + sshKeys.getSshPrivateKey());
        System.out.println("SSH public key value: \n" + sshKeys.getSshPublicKey());

        //=============================================================
        // Create an Azure Container Service with Kubernetes orchestration

        System.out.println(
                "Creating an Azure Container Service with Kubernetes ochestration and one agent (virtual machine)");

        Date t1 = new Date();

        ContainerService azureContainerService = azure.containerServices().define(acsName).withRegion(region)
                .withNewResourceGroup(rgName).withKubernetesOrchestration()
                .withServicePrincipal(servicePrincipalClientId, servicePrincipalSecret).withLinux()
                .withRootUsername(rootUserName).withSshKey(sshKeys.getSshPublicKey())
                .withMasterNodeCount(ContainerServiceMasterProfileCount.MIN)
                .withMasterLeafDomainLabel("dns-" + acsName).defineAgentPool("agentpool").withVMCount(1)
                .withVMSize(ContainerServiceVMSizeTypes.STANDARD_D1_V2).withLeafDomainLabel("dns-ap-" + acsName)
                .attach().create();

        Date t2 = new Date();
        System.out.println("Created Azure Container Service: (took " + ((t2.getTime() - t1.getTime()) / 1000)
                + " seconds) " + azureContainerService.id());
        Utils.print(azureContainerService);

        //=============================================================
        // Create an Azure Container Registry to store and manage private Docker container images

        System.out.println("Creating an Azure Container Registry");

        t1 = new Date();

        Registry azureRegistry = azure.containerRegistries().define(acrName).withRegion(region)
                .withNewResourceGroup(rgName).withNewStorageAccount(saName).withRegistryNameAsAdminUser()
                .create();

        t2 = new Date();
        System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000)
                + " seconds) " + azureRegistry.id());
        Utils.print(azureRegistry);

        //=============================================================
        // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry

        RegistryListCredentials acrCredentials = azureRegistry.listCredentials();
        DockerClient dockerClient = DockerUtils.createDockerClient(azure, rgName, region,
                azureRegistry.loginServerUrl(), acrCredentials.username(),
                acrCredentials.passwords().get(0).value());

        //=============================================================
        // Pull a temp image from public Docker repo and create a temporary container from that image
        // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR

        dockerClient.pullImageCmd(dockerImageName).withTag(dockerImageTag).exec(new PullImageResultCallback())
                .awaitSuccess();
        System.out.println("List local Docker images:");
        List<Image> images = dockerClient.listImagesCmd().withShowAll(true).exec();
        for (Image image : images) {
            System.out.format("\tFound Docker image %s (%s)\n", image.getRepoTags()[0], image.getId());
        }

        CreateContainerResponse dockerContainerInstance = dockerClient
                .createContainerCmd(dockerImageName + ":" + dockerImageTag).withName(dockerContainerName)
                .withCmd("/hello").exec();
        System.out.println("List Docker containers:");
        List<Container> dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec();
        for (Container container : dockerContainers) {
            System.out.format("\tFound Docker container %s (%s)\n", container.getImage(), container.getId());
        }

        //=============================================================
        // Commit the new container

        String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName;
        String dockerImageId = dockerClient.commitCmd(dockerContainerInstance.getId())
                .withRepository(privateRepoUrl).withTag("latest").exec();

        // We can now remove the temporary container instance
        dockerClient.removeContainerCmd(dockerContainerInstance.getId()).withForce(true).exec();

        //=============================================================
        // Push the new Docker image to the Azure Container Registry

        dockerClient.pushImageCmd(privateRepoUrl).withAuthConfig(dockerClient.authConfig())
                .exec(new PushImageResultCallback()).awaitSuccess();

        // Remove the temp image from the local Docker host
        try {
            dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec();
        } catch (NotFoundException e) {
            // just ignore if not exist
        }

        //=============================================================
        // Verify that the image we saved in the Azure Container registry can be pulled and instantiated locally

        dockerClient.pullImageCmd(privateRepoUrl).withAuthConfig(dockerClient.authConfig())
                .exec(new PullImageResultCallback()).awaitSuccess();
        System.out.println(
                "List local Docker images after pulling sample image from the Azure Container Registry:");
        images = dockerClient.listImagesCmd().withShowAll(true).exec();
        for (Image image : images) {
            System.out.format("\tFound Docker image %s (%s)\n", image.getRepoTags()[0], image.getId());
        }
        dockerContainerInstance = dockerClient.createContainerCmd(privateRepoUrl)
                .withName(dockerContainerName + "-private").withCmd("/hello").exec();
        System.out.println(
                "List Docker containers after instantiating container from the Azure Container Registry sample image:");
        dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec();
        for (Container container : dockerContainers) {
            System.out.format("\tFound Docker container %s (%s)\n", container.getImage(), container.getId());
        }

        //=============================================================
        // Download the Kubernetes config file from one of the master virtual machines

        azureContainerService = azure.containerServices().getByResourceGroup(rgName, acsName);
        System.out.println("Found Kubernetes master at: " + azureContainerService.masterFqdn());

        shell = SSHShell.open(azureContainerService.masterFqdn(), 22, rootUserName,
                sshKeys.getSshPrivateKey().getBytes());

        String kubeConfigContent = shell.download("config", ".kube", true);
        System.out.println("Found Kubernetes config:\n" + kubeConfigContent);

        //=============================================================
        // Instantiate the Kubernetes client using the downloaded ".kube/config" file content
        //     The Kubernetes client API requires setting an environment variable pointing at a real file;
        //        we will create a temporary file that will be deleted automatically when the sample exits

        File tempKubeConfigFile = File.createTempFile("kube", ".config",
                new File(System.getProperty("java.io.tmpdir")));
        tempKubeConfigFile.deleteOnExit();
        BufferedWriter buffOut = new BufferedWriter(new FileWriter(tempKubeConfigFile));
        buffOut.write(kubeConfigContent);
        buffOut.close();

        System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, tempKubeConfigFile.getPath());
        Config config = new Config();
        KubernetesClient kubernetesClient = new DefaultKubernetesClient(config);

        //=============================================================
        // List all the nodes available in the Kubernetes cluster

        System.out.println(kubernetesClient.nodes().list());

        //=============================================================
        // Create a namespace where all the sample Kubernetes resources will be created

        Namespace ns = new NamespaceBuilder().withNewMetadata().withName(acsNamespace)
                .addToLabels("acr", "sample").endMetadata().build();
        try {
            System.out.println("Created namespace" + kubernetesClient.namespaces().create(ns));
        } catch (Exception ignored) {
        }

        Thread.sleep(5000);
        for (Namespace namespace : kubernetesClient.namespaces().list().getItems()) {
            System.out.println("\tFound Kubernetes namespace: " + namespace.toString());
        }

        //=============================================================
        // Create a secret of type "docker-repository" that will be used for downloading the container image from
        //     our Azure private container repo

        String basicAuth = new String(Base64.encodeBase64(
                (acrCredentials.username() + ":" + acrCredentials.passwords().get(0).value()).getBytes()));
        HashMap<String, String> secretData = new HashMap<>(1);
        String dockerCfg = String.format("{ \"%s\": { \"auth\": \"%s\", \"email\": \"%s\" } }",
                azureRegistry.loginServerUrl(), basicAuth, "acrsample@azure.com");

        dockerCfg = new String(Base64.encodeBase64(dockerCfg.getBytes("UTF-8")), "UTF-8");
        secretData.put(".dockercfg", dockerCfg);
        SecretBuilder secretBuilder = new SecretBuilder().withNewMetadata().withName(acsSecretName)
                .withNamespace(acsNamespace).endMetadata().withData(secretData)
                .withType("kubernetes.io/dockercfg");

        System.out.println("Creating new secret: "
                + kubernetesClient.secrets().inNamespace(acsNamespace).create(secretBuilder.build()));

        Thread.sleep(5000);

        for (Secret kubeS : kubernetesClient.secrets().inNamespace(acsNamespace).list().getItems()) {
            System.out.println("\tFound secret: " + kubeS);
        }

        //=============================================================
        // Create a replication controller for our image stored in the Azure Container Registry

        ReplicationController rc = new ReplicationControllerBuilder().withNewMetadata().withName("acrsample-rc")
                .withNamespace(acsNamespace).addToLabels("acrsample-nginx", "nginx").endMetadata().withNewSpec()
                .withReplicas(2).withNewTemplate().withNewMetadata().addToLabels("acrsample-nginx", "nginx")
                .endMetadata().withNewSpec().addNewImagePullSecret(acsSecretName).addNewContainer()
                .withName("acrsample-pod-nginx").withImage(privateRepoUrl).addNewPort().withContainerPort(80)
                .endPort().endContainer().endSpec().endTemplate().endSpec().build();

        System.out.println("Creating a replication controller: "
                + kubernetesClient.replicationControllers().inNamespace(acsNamespace).create(rc));
        Thread.sleep(5000);

        rc = kubernetesClient.replicationControllers().inNamespace(acsNamespace).withName("acrsample-rc").get();
        System.out.println("Found replication controller: " + rc.toString());

        for (Pod pod : kubernetesClient.pods().inNamespace(acsNamespace).list().getItems()) {
            System.out.println("\tFound Kubernetes pods: " + pod.toString());
        }

        //=============================================================
        // Create a Load Balancer service that will expose the service to the world

        Service lbService = new ServiceBuilder().withNewMetadata().withName(acsLbIngressName)
                .withNamespace(acsNamespace).endMetadata().withNewSpec().withType("LoadBalancer").addNewPort()
                .withPort(80).withProtocol("TCP").endPort().addToSelector("acrsample-nginx", "nginx").endSpec()
                .build();

        System.out.println("Creating a service: "
                + kubernetesClient.services().inNamespace(acsNamespace).create(lbService));

        Thread.sleep(5000);

        System.out.println("\tFound service: "
                + kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get());

        //=============================================================
        // Wait until the external IP becomes available

        int timeout = 30 * 60 * 1000; // 30 minutes
        String matchIPV4 = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$";

        while (timeout > 0) {
            try {
                List<LoadBalancerIngress> lbIngressList = kubernetesClient.services().inNamespace(acsNamespace)
                        .withName(acsLbIngressName).get().getStatus().getLoadBalancer().getIngress();
                if (lbIngressList != null && !lbIngressList.isEmpty() && lbIngressList.get(0) != null
                        && lbIngressList.get(0).getIp().matches(matchIPV4)) {
                    System.out.println("\tFound ingress IP: " + lbIngressList.get(0).getIp());
                    timeout = 0;
                }
            } catch (Exception ignored) {
            }

            if (timeout > 0) {
                timeout -= 30000; // 30 seconds
                Thread.sleep(30000);
            }
        }

        // Clean-up
        kubernetesClient.namespaces().delete(ns);

        shell.close();
        shell = null;

        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
            if (shell != null) {
                shell.close();
            }
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}

From source file:emperior.Main.java

public static void copyFile(String filePath, File targetLocation) throws Exception {
    File f = new File(filePath);
    if (f.isFile()) {

        targetLocation.mkdirs();/* w w w  . j av  a  2s.c  om*/

        System.out.println(filePath);

        //         String [] pathElements = filePath.split("/");
        //         String [] pathElements = filePath.split("\\\\|/");
        String[] pathElements = filePath.split("\\\\");

        //         if(pathElements.length > 0){
        //            System.out.println("[test] " + targetLocation + File.separator + filePath.substring(0, filePath.lastIndexOf(System.getProperty("file.separator"))));
        //            targetLocation = new File(targetLocation + File.separator + filePath.substring(0, filePath.lastIndexOf(System.getProperty("file.separator"))));
        //            targetLocation.mkdirs();
        //         }

        JEditorPane editor = mainFrame.editors.get(filePath);

        String copypath = targetLocation + File.separator + pathElements[pathElements.length - 1];

        System.out.println("[test] " + copypath);

        Main.addLineToLogFile("[File] saving to: " + copypath);

        FileWriter fstream = new FileWriter(copypath);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(editor.getText());
        // Close the output stream
        out.close();

    }

}

From source file:net.arccotangent.pacchat.net.Client.java

public static void sendMessage(String msg, String ip_address) {
    client_log.i("Sending message to " + ip_address);
    client_log.i("Connecting to server...");

    PublicKey pub;/*w w w  .j av  a 2s  . c o  m*/
    PrivateKey priv;
    Socket socket;
    BufferedReader input;
    BufferedWriter output;

    client_log.i("Checking for recipient's public key...");
    if (KeyManager.checkIfIPKeyExists(ip_address)) {
        client_log.i("Public key found.");
    } else {
        client_log.i("Public key not found, requesting key from their server.");
        try {
            Socket socketGetkey = new Socket();
            socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
            BufferedReader inputGetkey = new BufferedReader(
                    new InputStreamReader(socketGetkey.getInputStream()));
            BufferedWriter outputGetkey = new BufferedWriter(
                    new OutputStreamWriter(socketGetkey.getOutputStream()));

            outputGetkey.write("301 getkey");
            outputGetkey.newLine();
            outputGetkey.flush();

            String pubkeyB64 = inputGetkey.readLine();
            byte[] pubEncoded = Base64.decodeBase64(pubkeyB64);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            outputGetkey.close();
            inputGetkey.close();

            KeyManager.saveKeyByIP(ip_address, keyFactory.generatePublic(pubSpec));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            client_log.e("Error saving recipient's key!");
            e.printStackTrace();
        }
    }

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(ip_address), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        client_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        client_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        client_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        client_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    pub = KeyManager.loadKeyByIP(ip_address);
    priv = Main.getKeypair().getPrivate();

    String cryptedMsg = MsgCrypto.encryptAndSignMessage(msg, pub, priv);
    try {
        client_log.i("Sending message to recipient.");
        output.write("200 encrypted message");
        output.newLine();
        output.write(cryptedMsg);
        output.newLine();
        output.flush();

        String ack = input.readLine();
        switch (ack) {
        case "201 message acknowledgement":
            client_log.i("Transmission successful, received server acknowledgement.");
            break;
        case "202 unable to decrypt":
            client_log.e(
                    "Transmission failure! Server reports that the message could not be decrypted. Did your keys change? Asking recipient for key update.");
            kuc_id++;
            KeyUpdateClient kuc = new KeyUpdateClient(kuc_id, ip_address);
            kuc.start();
            break;
        case "203 unable to verify":
            client_log.w("**********************************************");
            client_log.w(
                    "Transmission successful, but the receiving server reports that the authenticity of the message could not be verified!");
            client_log.w(
                    "Someone may be tampering with your connection! This is an unlikely, but not impossible scenario!");
            client_log.w(
                    "If you are sure the connection was not tampered with, consider requesting a key update.");
            client_log.w("**********************************************");
            break;
        case "400 invalid transmission header":
            client_log.e(
                    "Transmission failure! Server reports that the message is invalid. Try updating your software and have the recipient do the same. If this does not fix the problem, report the error to developers.");
            break;
        default:
            client_log.w("Server responded with unexpected code: " + ack);
            client_log.w("Transmission might not have been successful.");
            break;
        }

        output.close();
        input.close();
    } catch (IOException e) {
        client_log.e("Error sending message to recipient!");
        e.printStackTrace();
    }
}

From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java

public static <T> void collection2Text(Collection<T> c, String filename, String header) {
    BufferedWriter bw = IOUtils.getBufferedWriter(filename);
    try {/*from www.ja  v a  2  s.  c  o  m*/
        if (header != null) {
            bw.write(header);
            bw.newLine();
        }
        for (Iterator<T> iterator = c.iterator(); iterator.hasNext();) {

            bw.write(iterator.next().toString());
            bw.newLine();
        }
        bw.flush();
        bw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:mt.LengthDistribution.java

public static void WriteLengthdistroFile(ArrayList<File> AllMovies, XYSeries counterseries, int framenumber) {

    try {//from  w  w  w . j a  va2  s.  c om

        File ratesfile = new File(AllMovies.get(0).getParentFile() + "//" + "Length-Distribution At T " + " = "
                + framenumber + ".txt");

        if (framenumber == 0)
            ratesfile = new File(AllMovies.get(0).getParentFile() + "//" + "Mean Length-Distribution" + ".txt");

        FileWriter fw = new FileWriter(ratesfile);

        BufferedWriter bw = new BufferedWriter(fw);

        bw.write("\tLength(real units) \tCount\n");

        for (int index = 0; index < counterseries.getItems().size(); ++index) {

            double Count = counterseries.getX(index).doubleValue();
            double Length = counterseries.getY(index).doubleValue();

            bw.write("\t" + Length + "\t" + "\t" + Count + "\t" + "\n");

        }

        bw.close();
        fw.close();

    }

    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.dexels.navajo.tipi.dev.server.appmanager.impl.UnsignJarTask.java

private static void cleanManifest(File manifest, File outputManifest, List<String> extraHeaders)
        throws IOException {

    BufferedReader fr = null;/*w w  w.ja  v a  2 s  .  c  o  m*/
    List<StringBuffer> manifestheaders;
    try {
        fr = new BufferedReader(new FileReader(manifest));
        String line = null;
        manifestheaders = new ArrayList<StringBuffer>();
        StringBuffer current = null;
        do {
            line = fr.readLine();
            if (line == null) {
                continue;
            }
            if (line.startsWith(" ")) {
                current.append(line);
                current.append("\n");
            } else {
                if (current != null) {
                    manifestheaders.add(current);
                }
                current = new StringBuffer();
                current.append(line.trim());
                current.append("\n");
            }
        } while (line != null);
    } finally {
        if (fr != null) {
            try {
                fr.close();
            } catch (Exception e) {
            }
        }
    }
    BufferedWriter fw = null;
    try {
        fw = new BufferedWriter(new FileWriter(outputManifest));
        List<StringBuffer> output = new ArrayList<StringBuffer>();

        for (StringBuffer header : manifestheaders) {
            if (checkLine(header.toString())) {
                output.add(header);
                fw.write(header.toString());
            }
        }
        for (String header : extraHeaders) {
            fw.write(header + "\n");
        }
    } finally {
        if (fw != null) {
            try {
                fw.close();
            } catch (Exception e) {
            }
        }
    }

}

From source file:hadoop.UIUCWikifierAppHadoop.java

/**
 * Read in NER and NE default config files, write out new config files
 * with appropriate paths then save config file and return its location
 * @param pathToWikifierFiles/*from w ww .  j  a v a  2  s . co m*/
 * @return
 * @throws IOException 
 * @throws FileNotFoundException 
 */
private static String[] writeNewConfigFiles(String pathToWikifierFiles)
        throws FileNotFoundException, IOException {
    String[] configFiles = new String[3];

    //read in old ner config parameters and change
    List<String> nerConfigLines = IOUtils
            .readLines(new FileInputStream(new File(pathToWikifierFiles + "/" + pathToDefaultNERConfigFile)));
    List<String> newNERConfigLines = new ArrayList<String>();
    for (String l : nerConfigLines) {
        String[] values = l.split("\\t+");
        StringBuilder newLine = new StringBuilder();
        for (String value : values) {
            if (value.contains("/")) {
                newLine.append(pathToWikifierFiles + "/" + value);
                newLine.append("\t");
            } else {
                newLine.append(value);
                newLine.append("\t");
            }
        }
        newNERConfigLines.add(newLine.toString().trim());
    }

    //write out new config parameters
    File newNERConfigFile = File.createTempFile("NER.config", ".tmp");
    newNERConfigFile.deleteOnExit();
    configFiles[0] = newNERConfigFile.getAbsolutePath();
    BufferedWriter nerWriter = new BufferedWriter(new FileWriter(newNERConfigFile));
    for (String l : newNERConfigLines) {
        System.out.println(l);
        nerWriter.write(l + "\n");
    }
    nerWriter.close();

    //read in old ne config parameters and change
    List<String> neConfigLines = IOUtils
            .readLines(new FileInputStream(new File(pathToWikifierFiles + "/" + pathToDefaultNEConfigFile)));
    List<String> newNEConfigLines = new ArrayList<String>();
    for (String l : neConfigLines) {
        String[] values = l.split("=");
        String value = values[1];
        if (value.contains("/")) {
            String[] paths = value.split("\\s+");
            StringBuilder newValue = new StringBuilder();
            for (String path : paths) {
                newValue.append(pathToWikifierFiles + "/" + path);
                newValue.append(" ");
            }
            StringBuilder newLine = new StringBuilder();
            newLine.append(values[0]);
            newLine.append("=");
            newLine.append(newValue.toString().trim());
            newNEConfigLines.add(newLine.toString());
        } else {
            newNEConfigLines.add(l);
        }
    }
    //write out new config parameters
    File newNEConfigFile = File.createTempFile("config.txt", ".tmp");
    newNEConfigFile.deleteOnExit();
    configFiles[1] = newNEConfigFile.getAbsolutePath();
    BufferedWriter neWriter = new BufferedWriter(new FileWriter(newNEConfigFile));
    for (String l : newNEConfigLines) {
        neWriter.write(l + "\n");
    }
    neWriter.close();

    //read in old wordnet properties
    List<String> wordNetPropertiesLines = IOUtils
            .readLines(new FileInputStream(new File(pathToWikifierFiles + "/" + pathToDefaultJWNLConfigFile)));
    List<String> newWordNetPropertiesLines = new ArrayList<String>();
    String replacementString = pathToWikifierFiles + "/data/WordNet/";
    String stringToReplace = "data/WordNet/";
    for (String l : wordNetPropertiesLines) {
        if (l.contains("dictionary_path")) {
            newWordNetPropertiesLines.add(l.replace(stringToReplace, replacementString));
        } else {
            newWordNetPropertiesLines.add(l);
        }
    }
    File newWNConfigFile = File.createTempFile("jwnl_properties.xml", ".tmp");
    newWNConfigFile.deleteOnExit();
    configFiles[2] = newWNConfigFile.getAbsolutePath();
    BufferedWriter wnWriter = new BufferedWriter(new FileWriter(newWNConfigFile));
    for (String l : newWordNetPropertiesLines) {
        wnWriter.write(l + "\n");
    }
    wnWriter.close();

    return configFiles;

}

From source file:csv.FileManager.java

static public boolean appendItems(String fileName, ArrayList<ArrayList<String>> data,
        boolean firstRowIsHeader) {
    try {/* w ww .  j a v  a2 s . c  om*/
        BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
        CSVWriter writer = new CSVWriter(out);
        String[] t = new String[0];
        for (ArrayList<String> row : data) {
            if (!firstRowIsHeader) {
                boolean found = false;
                for (String str : row) {
                    if (!str.isEmpty()) {
                        found = true;
                    }
                }
                if (found)
                    writer.writeNext(row.toArray(t));
            } else
                firstRowIsHeader = false;
        }
        out.close();
        return true;
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return false;
    }
}

From source file:fi.mikuz.boarder.util.FileProcessor.java

public static void saveGraphicalSoundboardHolder(String boardName, GraphicalSoundboardHolder boardHolder)
        throws IOException {
    synchronized (boardSaveFileLock) {
        File boardDir = constructBoardPath(boardName);
        File boardFile = new File(boardDir, boardSaveFileName);
        File tmpBoardFile = new File(boardDir, boardTempSaveFileName);

        changeBoardDirectoryReferences(boardHolder, boardDir, SoundboardMenu.mLocalBoardDir);

        boardDir.mkdirs();/*w  w  w  .j a  v a  2  s . c  o  m*/
        attemptBackup(tmpBoardFile);

        if (boardDir.exists() == false) {
            boardDir.mkdirs();
        }

        BufferedWriter tmpOut = new BufferedWriter(new FileWriter(tmpBoardFile));

        XStream xstream = XStreamUtil.graphicalBoardXStream();
        xstream.toXML(boardHolder, tmpOut);
        tmpOut.close();

        BufferedReader in = new BufferedReader(new FileReader(tmpBoardFile));
        BufferedWriter out = new BufferedWriter(new FileWriter(boardFile));
        IOUtils.copy(in, out);
        in.close();
        out.close();

        tmpBoardFile.delete();
    }
}