Example usage for java.io FileWriter write

List of usage examples for java.io FileWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:fr.paris.lutece.maven.FileUtils.java

/**
 * Write to the given file//  w  w  w .j a  v  a2  s.c  o m
 * @param strContent the content to write
 * @param strFile the file
 */
public static void writeToFile(String strContent, String strFile) {
    FileWriter fw = null;

    try {
        fw = new FileWriter(strFile, false);
        fw.write(strContent);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fw);
    }
}

From source file:com.abid_mujtaba.fetchheaders.models.Account.java

private static void writeAccountsToJson() // Reads all Account objects (some of them updated) and uses them to write this data to accounts.json
{
    try {/*  www. j av  a2 s  .c  o  m*/
        JSONObject jRoot = new JSONObject();
        JSONArray jAccounts = new JSONArray();

        for (int ii = 0; ii < sNumOfInstances; ii++) {
            JSONObject jAccount = new JSONObject();
            Account account = sInstances.get(ii);

            jAccount.put("name", account.name());
            jAccount.put("host", account.host());
            jAccount.put("username", account.username());
            jAccount.put("password", account.password());

            jAccounts.put(jAccount);
        }

        jRoot.put("accounts", jAccounts);

        // Save JSON to accounts.json
        FileWriter fw = new FileWriter(new File(Resources.INTERNAL_FOLDER, Settings.ACCOUNTS_JSON_FILE)); // Write root JSON object to file info.json
        fw.write(jRoot.toString());
        fw.flush();
        fw.close();
    } catch (JSONException e) {
        Log.e(Resources.LOGTAG, "Exception raised while manipulate JSON objects.", e);
    } catch (IOException e) {
        Log.e(Resources.LOGTAG, "Exception raised while saving content to json file.", e);
    }
}

From source file:main.java.utils.Utility.java

public static void deleteLinesFromFile(String filename, int startline, int numlines) {
    try {//www. j a v a 2 s. c  om
        BufferedReader br = new BufferedReader(new FileReader(filename));

        //String buffer to store contents of the file
        StringBuffer sb = new StringBuffer("");

        //Keep track of the line number
        int linenumber = 1;
        String line;

        while ((line = br.readLine()) != null) {
            //Store each valid line in the string buffer
            if (linenumber < startline || linenumber >= startline + numlines)
                sb.append(line + "\n");
            linenumber++;
        }

        if (startline + numlines > linenumber)
            System.out.println("End of file reached.");
        br.close();

        FileWriter fw = new FileWriter(new File(filename));

        //Write entire string buffer into the file
        fw.write(sb.toString());
        fw.close();

    } catch (Exception e) {
        System.out.println("Something went horribly wrong: " + e.getMessage());
    }
}

From source file:Main.java

public static boolean writeFile(String filePath, String fileName, String content, boolean append) {
    FileWriter fileWriter = null;
    boolean result = false;
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
        try {/*from  w w  w .ja  v a 2s  .  co m*/

            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Log.i("file", filePath);
            fileWriter = new FileWriter(filePath + fileName, append);
            fileWriter.write(content);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("file", e.toString());
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    return result;
}

From source file:net.sourceforge.docfetcher.CommandLineHandler.java

/**
 * Handles command line text extraction. Returns false if the program should
 * terminate after executing this method, and returns true if the program is
 * allowed to proceed.//from  www  .ja  v a2  s . co  m
 */
private static boolean handleTextExtraction(CommandLine line) {
    if (!line.hasOption(EXTRACT) && !line.hasOption(EXTRACT_DIR))
        return true;

    // Create inclusion and exclusion filters
    Pattern includeFilter = null;
    Pattern excludeFilter = null;
    try {
        String includeString = line.getOptionValue(INCLUDE); // may be null
        includeFilter = Pattern.compile(includeString);
    } catch (Exception e1) {
        // Ignore
    }
    try {
        String excludeString = line.getOptionValue(EXCLUDE); // may be null
        excludeFilter = Pattern.compile(excludeString);
    } catch (Exception e1) {
        // Ignore
    }

    // Get sources and destination
    boolean writeToDir = false;
    String[] args1 = null;
    if (line.hasOption(EXTRACT)) {
        args1 = line.getOptionValues(EXTRACT);
    } else {
        writeToDir = true;
        args1 = line.getOptionValues(EXTRACT_DIR);
    }
    if (args1 == null)
        args1 = new String[0];
    String[] args2 = line.getArgs();
    String[] args = UtilList.concatenate(args1, args2, new String[args1.length + args2.length]);
    if (args.length < 2) {
        System.out.println("Text extraction requires at least one source and one destination.");
        return false;
    }

    // Create source file objects, check for existence
    int lastIndex = args.length - 1;
    File[] topLevelSources = new File[lastIndex];
    for (int i = 0; i < topLevelSources.length; i++) {
        String path = args[i];
        File file = new File(path);
        if (!file.exists()) {
            System.out.println("File not found: " + path);
            return false;
        }
        topLevelSources[i] = file;
    }

    // Check validity of destination
    File dest = new File(args[lastIndex]);
    if (writeToDir) {
        if (dest.exists()) {
            if (!dest.isDirectory()) {
                System.out.println("Not a directory: " + dest.getAbsolutePath());
                return false;
            }
        } else {
            if (!dest.mkdirs()) {
                System.out.println("Could not create directory: " + dest.getAbsolutePath());
                return false;
            }
        }
    }

    /*
     * The source files are collected beforehand because
     * 1) the text output will depend on the number of files to process,
     * so we first have to determine how many files there are
     * 2) the target file(s) might lie inside one of the source directories,
     * so we first collect all source files in order to avoid confusion
     * 3) by using a Map, we make sure there aren't any duplicate sources.
     */
    Map<File, Parser> sources = new LinkedHashMap<File, Parser>();
    for (File topLevelSource : topLevelSources)
        collect(topLevelSource, sources, includeFilter, excludeFilter, true);
    int nSources = sources.size(); // must be set *after* filling the sources list!

    // Perform text extraction
    if (writeToDir) {
        int i = 1;
        for (Entry<File, Parser> item : sources.entrySet()) {
            File source = item.getKey();
            System.out.println("Extracting (" + i + "/" + nSources + "): " + source.getName());
            try {
                File outFile = UtilFile.getNewFile(dest, source.getName() + ".txt");
                String text = item.getValue().renderText(source);
                FileWriter writer = new FileWriter(outFile, false);
                writer.write(text);
                writer.close();
            } catch (Exception e) {
                System.out.println("  Error: " + e.getMessage());
            }
            i++;
        }
    } else {
        // First check that the destination is not one of the source files
        for (File source : sources.keySet()) {
            if (source.equals(dest)) {
                System.out.println("Invalid input: Destination is identical to one of the source files.");
                return false;
            }
        }
        // If there's only one file to process, don't decorate the text output
        if (nSources == 1) {
            Entry<File, Parser> item = sources.entrySet().iterator().next();
            System.out.println("Extracting: " + item.getKey().getName());
            try {
                String text = item.getValue().renderText(item.getKey());
                FileWriter writer = new FileWriter(dest);
                writer.write(text);
                writer.close();
            } catch (Exception e) {
                System.out.println("  Error: " + e.getMessage());
            }
        }
        // Multiple files to process:
        else {
            try {
                FileWriter writer = new FileWriter(dest, false); // overwrite
                int i = 1;
                for (Entry<File, Parser> item : sources.entrySet()) {
                    File source = item.getKey();
                    System.out.println("Extracting (" + i + "/" + nSources + "): " + source.getName());
                    try {
                        String text = item.getValue().renderText(source); // This may fail, so do it first
                        writer.write("Source: " + source.getAbsolutePath() + Const.LS);
                        writer.write("============================================================" + Const.LS);
                        writer.write(text);
                        writer.write(Const.LS + Const.LS + Const.LS);
                    } catch (Exception e) {
                        System.out.println("  Error: " + e.getMessage());
                    }
                    i++;
                }
                writer.close();
            } catch (IOException e) {
                System.out.println("Can't write to file: " + e.getMessage());
            }
        }
    }
    return false;
}

From source file:com.netcrest.pado.internal.security.AESCipher.java

private static byte[] getUserPrivateKey() throws IOException {
    byte[] privateKey = null;

    String estr;//w w w . j a  v a 2 s .c om
    String certificateFilePath = PadoUtil.getProperty(Constants.PROP_SECURITY_AES_USER_CERTIFICATE,
            "security/user.cer");
    if (certificateFilePath.startsWith("/") == false) {

        // TODO: Make server files relative to PADO_HOME also.
        if (PadoUtil.isPureClient()) {
            String padoHome = PadoUtil.getProperty(Constants.PROP_HOME_DIR);
            certificateFilePath = padoHome + "/" + certificateFilePath;
        }
    }
    File file = new File(certificateFilePath);
    if (file.exists() == false) {
        FileWriter writer = null;
        try {
            privateKey = AESCipher.getPrivateKey();
            Base64 base64 = new Base64(0); // no line breaks
            estr = base64.encodeToString(privateKey);
            writer = new FileWriter(file);
            writer.write(estr);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    } else {
        FileReader reader = null;
        try {
            reader = new FileReader(file);
            StringBuffer buffer = new StringBuffer(2048);
            int c;
            while ((c = reader.read()) != -1) {
                buffer.append((char) c);
            }
            estr = buffer.toString();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
    Base64 base64 = new Base64(0); // no line breaks
    privateKey = base64.decode(estr);
    return privateKey;
}

From source file:com.me.edu.Servlet.ElasticSearch_Backup.java

public static String getSentence(String input) {
    String paragraph = input;//ww w. j  a v a 2s. co m
    Reader reader = new StringReader(paragraph);
    DocumentPreprocessor dp = new DocumentPreprocessor(reader);
    List<String> sentenceList = new ArrayList<String>();

    for (List<HasWord> sentence : dp) {
        String sentenceString = Sentence.listToString(sentence);
        sentenceList.add(sentenceString.toString());
    }
    String sent = "";
    for (String sentence : sentenceList) {
        System.out.println(sentence);
        sent = sent + " " + sentence + "\n";
    }
    try {

        FileWriter file = new FileWriter("Sentences.txt");
        file.write(sent.toString());
        file.flush();
        file.close();

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

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.FileUtil.java

/**
 * Writes the given content in the given file
 *
 * @param content the content to add/*from w  ww  .  ja  va  2 s.  c o m*/
 * @param file    the file into which to write the content
 * @throws IOException
 */
public static void writeContentToFile(final String content, final File file) throws IOException {

    FileWriter fileWriter = null;

    try {
        fileWriter = new FileWriter(file);
        fileWriter.write(content);

    } finally {

        if (fileWriter != null) {

            fileWriter.flush();
            fileWriter.close();
        }
    }
}

From source file:com.xauto.ux.Emf2.java

@SuppressWarnings("deprecation")
    public static void extractPicturesFromDoc(String docName) throws Exception {
        Document doc = new Document(docName + ".docx");
        Integer emfOrWmfIndex = 1;
        Integer pngOrJpegIndex = 100;
        Integer bmpOrPictIndex = 10000;
        Integer otherIndex = 1000;

        String outDir = "out" + File.separator + docName + File.separator;
        FileUtils.forceMkdir(new File(outDir));
        FileWriter html = new FileWriter(outDir + "out.html");
        html.write(
                "<html>\n<head><meta http-equiv=\"x-ua-compatible\" content=\"IE=edge,chrome=1\"></head><body>\n");

        for (AsposeDrawingType type : AsposeDrawingType.values()) {
            Node[] drawArray = doc.getChildNodes(type.code(), true).toArray();
            int index = 0;
            logger.info("type={};count={}", type, drawArray.length);
            for (Node n : drawArray) {
                WordDrawing node = null;
                DrawingML dml = null;// ww  w.ja va2s  . co m
                Shape s = null;
                if (n instanceof Shape) {
                    s = (Shape) n;
                    node = new WordDrawing(s);
                } else if (n instanceof DrawingML) {
                    dml = (DrawingML) n;
                    node = new WordDrawing(dml);
                }

                index++;
                IImageData img = node.getImageData();
                BufferedImage bi = img.toImage();
                AposeWordImageType asposeWordImageType = AposeWordImageType.fromCode(img.getImageType());
                String extn = null;
                String trimmedDrawingName = node.getName().replace(" ", "") + index;
                ImageSize is = img.getImageSize();
                long resolution = 600;
                int scale = 1000;
                Graphics2D gd = bi.createGraphics();
                gd.getClipBounds();
                int jpegQual = 70;
                boolean antiAlias = true;
                boolean highQualityRendering = true;
                try {
                    extn = FileFormatUtil.imageTypeToExtension(img.getImageType());
                } catch (IllegalArgumentException e) {
                    extn = "unknown";
                }

                String drawingName = node.getName();
                if (StringUtils.isBlank(drawingName)) {
                    if (node.getNode() instanceof Shape) {
                        Shape s = (Shape) node.getNode();
                        Node cell = null;
                        Node parent = s.getParentNode();
                        while (parent.getNodeType() != NodeType.ROW) {
                            if (parent.getNodeType() == NodeType.CELL) {
                                cell = parent;
                            }
                            parent = parent.getParentNode();
                        }
                        Row picturesRow = (Row) parent;
                        Row captionsRow = (Row) picturesRow.getPreviousSibling();
                        Node[] currentPicturesRowCells = picturesRow.getChildNodes(NodeType.CELL, true).toArray();
                        int foundIndex = 0;
                        for (Node n : currentPicturesRowCells) {
                            if (n == cell) {
                                break;
                            }
                            foundIndex++;
                        }
                        Cell captionCell = (Cell) captionsRow.getChild(NodeType.CELL, foundIndex, true);
                        StringBuilder sb = new StringBuilder();
                        Paragraph[] ps = captionCell.getParagraphs().toArray();
                        for (Paragraph p : ps) {
                            Run[] rs = p.getRuns().toArray();
                            for (Run r : rs) {
                                r.getDirectRunAttrsCount();
                                sb.append(r.getText());
                            }
                        }
                        drawingName = sb.toString().replace("SEQ Figure \\* ARABIC ", "");
                    }
                }

                logger.debug(
                        "imageType={};name={};hasImage()={};imageByteSize={};isLink={};imageSize.Width={};imageSize.Height={};"
                                + "imageSize.HorRes={};imageSize.VertRes={};imageSize.WPoints={};imageSize.HPoints={};"
                                + "bufferedImageType={}; biHeight={}; biWidth={}; trimmedDrawingName={}; extn={};"
                                + "" + "bufferedImageInfo={};drawInfo={}",
                        asposeWordImageType, drawingName, img.hasImage(),
                        img.getImageBytes() == null ? 0 : img.getImageBytes().length, img.isLink(),
                        is.getWidthPixels(), is.getHeightPixels(), is.getHorizontalResolution(),
                        is.getVerticalResolution(), is.getWidthPoints(), is.getHeightPoints(),
                        AwtImageType.fromCode(bi.getType()), bi.getHeight(), bi.getWidth(), trimmedDrawingName,
                        extn, bi.toString(), node.toString());
                if (StringUtils.isBlank(node.getName())) {
                    if (dml != null) {
                        dml.getParentNode();
                        logger.debug("getAncestor={}", dml.getAncestor(DocumentProperty.class));
                    } else if (s != null) {
                        s.getExpandedRunPr_IInline(54);

                        logger.debug(s.toTxt() + s.getText());
                        @SuppressWarnings("unchecked")
                        NodeCollection<Node> ns = s.getChildNodes();
                        while (ns.iterator().hasNext()) {
                            Node n1 = (Node) ns.iterator().next();
                            n1.getText();
                        }
                        logger.debug("shape={}", s.getAncestor(DocumentProperty.class));
                        s.getParentParagraph();
                    }
                }
                if (asposeWordImageType == AposeWordImageType.UNKNOWN) {
                    otherIndex++;
                    continue;
                }
                if (img == null || asposeWordImageType == AposeWordImageType.NO_IMAGE) {
                    continue;
                }
                if (asposeWordImageType == AposeWordImageType.EMF
                        || asposeWordImageType == AposeWordImageType.WMF) {

                    ShapeRenderer sr = node.getShapeRenderer();
                    img.save(outDir + trimmedDrawingName + extn);
                    PngOptions pngOptions = new PngOptions();
                    if (asposeWordImageType == AposeWordImageType.EMF) {
                        EmfMetafileImage emf = new EmfMetafileImage(outDir + trimmedDrawingName + extn);
                        emf.save(outDir + trimmedDrawingName + "_buffered_emf.png", pngOptions);
                    } else {
                        WmfMetafileImage wmf = new WmfMetafileImage(outDir + trimmedDrawingName + extn);
                        wmf.save(outDir + trimmedDrawingName + "_buffered_emf.png", pngOptions);
                    }

                    trimmedDrawingName += "_" + scale + "_" + resolution + "_" + jpegQual + "_" + antiAlias + "_"
                            + highQualityRendering;
                    ImageSaveOptions pngSave = new ImageSaveOptions(com.aspose.words.SaveFormat.PNG);
                    pngSave.setResolution(resolution);
                    pngSave.setUseHighQualityRendering(highQualityRendering);
                    pngSave.setDmlRenderingMode(DmlRenderingMode.DRAWING_ML);
                    pngSave.setDmlEffectsRenderingMode(DmlEffectsRenderingMode.FINE);
                    pngSave.setUseAntiAliasing(antiAlias);
                    pngSave.setScale((float) scale / 1000);

                    ImageSaveOptions jpgSave = new ImageSaveOptions(SaveFormat.JPEG);
                    jpgSave.setUseHighQualityRendering(true);
                    jpgSave.setResolution(resolution);
                    jpgSave.setJpegQuality(jpegQual);
                    jpgSave.setScale((float) scale / 1000);

                    sr.save(outDir + trimmedDrawingName + ".png", pngSave);
                    BufferedImage savedPNG = ImageIO.read(new File(outDir + trimmedDrawingName + ".png"));
                    BufferedImage resizedFromSaved = Scalr.resize(savedPNG, Method.ULTRA_QUALITY, Mode.FIT_TO_WIDTH,
                            435);
                    BufferedImage resizedFromBi = Scalr.resize(bi, Method.ULTRA_QUALITY, Mode.FIT_TO_WIDTH, 435);
                    ImageIO.write(bi, "png", new File(outDir + trimmedDrawingName + "_buffered.png"));
                    ImageIO.write(resizedFromSaved, "png",
                            new File(outDir + trimmedDrawingName + "_resized_from_saved_scalr_antialias_435.png"));
                    ImageIO.write(resizedFromBi, "png",
                            new File(outDir + trimmedDrawingName + "_resized_from_bi_scalr_antialias_435.png"));
                    //sr.save(outDir+trimmedDrawingName+".jpg", jpgSave);

                    html.write("\t<div>\n\t\t\n\t\t<br>\n\t\t<hr><p align=center>.SVG figure: " + trimmedDrawingName
                            + "</p>\n\t\t<hr>\n\t\t<br>\n\t\t<br>\n\t\t<img src=\"" + trimmedDrawingName
                            + ".svg\" width=\"100%\" />\n\t</div>\n");

                    //convertToSVG(outputDir + docId + "\\", trimmedDrawingName, extn);
                    emfOrWmfIndex++;
                } else if (asposeWordImageType == AposeWordImageType.PNG
                        || asposeWordImageType == AposeWordImageType.JPEG) {
                    ShapeRenderer sr = node.getShapeRenderer();
                    ImageSaveOptions pngSave = new ImageSaveOptions(com.aspose.words.SaveFormat.PNG);
                    pngSave.setResolution(resolution);
                    pngSave.setUseHighQualityRendering(highQualityRendering);
                    pngSave.setDmlRenderingMode(DmlRenderingMode.DRAWING_ML);
                    pngSave.setDmlEffectsRenderingMode(DmlEffectsRenderingMode.FINE);
                    pngSave.setUseAntiAliasing(antiAlias);
                    pngSave.setScale((float) scale / 1000);
                    img.save(outDir + trimmedDrawingName + extn);
                    sr.save(outDir + trimmedDrawingName + "_DIRECT" + extn, pngSave);
                    if (is.getHeightPoints() > 99) {
                        html.write("\t<div>\n\t\t\n\t\t<br>\n\t\t<hr><p align=center>" + extn.toUpperCase()
                                + " figure: " + trimmedDrawingName
                                + "</p>\n\t\t<hr>\n\t\t<br>\n\t\t<br>\n\t\t<img src=\"" + trimmedDrawingName + extn
                                + "\" width=\"100%\" />\n\t</div>\n");
                    }
                    pngOrJpegIndex++;
                } else if (asposeWordImageType == AposeWordImageType.BMP
                        || asposeWordImageType == AposeWordImageType.PICT) {
                    img.save(outDir + bmpOrPictIndex + extn);
                    bmpOrPictIndex++;
                } else {
                    logger.info(
                            "PICT type={}; isLink={}; isLinkOnly={}; imageSize={}; sourceFileName={}; hasImage={}",
                            asposeWordImageType, img.isLink(), img.isLinkOnly(),
                            img.getImageSize().getHorizontalResolution(), img.getSourceFullName(), img.hasImage());
                }
            }
        }
        html.write("</body>\n</html>");
        html.close();
    }

From source file:com.alibaba.rocketmq.common.MixAll.java

public static final void string2FileNotSafe(final String str, final String fileName) throws IOException {
    File file = new File(fileName);
    File fileParent = file.getParentFile();
    if (fileParent != null) {
        fileParent.mkdirs();//from w  w w .  j av a 2  s  .co m
    }
    FileWriter fileWriter = null;

    try {
        fileWriter = new FileWriter(file);
        fileWriter.write(str);
    } catch (IOException e) {
        throw e;
    } finally {
        if (fileWriter != null) {
            try {
                fileWriter.close();
            } catch (IOException e) {
                throw e;
            }
        }
    }
}