Example usage for java.io FileOutputStream close

List of usage examples for java.io FileOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this file output stream and releases any system resources associated with this stream.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileOutputStream fileOut = new FileOutputStream("data.txt");
    BufferedOutputStream buffer = new BufferedOutputStream(fileOut);
    DataOutputStream dataOut = new DataOutputStream(buffer);
    dataOut.writeUTF("Hello!");
    dataOut.writeInt(4);//from   w ww  .  jav a 2s.  c  o  m
    dataOut.writeDouble(100.0);
    dataOut.close();
    buffer.close();
    fileOut.close();
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    SecretKey key = KeyGenerator.getInstance("DES").generateKey();

    // for CBC; must be 8 bytes
    byte[] initVector = new byte[] { 0x10, 0x10, 0x01, 0x04, 0x01, 0x01, 0x01, 0x02 };

    AlgorithmParameterSpec algParamSpec = new IvParameterSpec(initVector);
    Cipher m_encrypter = Cipher.getInstance("DES/CBC/PKCS5Padding");
    Cipher m_decrypter = Cipher.getInstance("DES/CBC/PKCS5Padding");

    m_encrypter.init(Cipher.ENCRYPT_MODE, key, algParamSpec);
    m_decrypter.init(Cipher.DECRYPT_MODE, key, algParamSpec);

    FileInputStream fis = new FileInputStream("cipherTest.in");
    FileOutputStream fos = new FileOutputStream("cipherTest.out");
    int dataInputSize = fis.available();

    byte[] inputBytes = new byte[dataInputSize];
    fis.read(inputBytes);/*from   ww w . j a  va2s.c om*/
    write(inputBytes, fos);
    fos.flush();
    fis.close();
    fos.close();

    String inputFileAsString = new String(inputBytes);
    System.out.println("INPUT FILE CONTENTS\n" + inputFileAsString + "\n");

    System.out.println("File encrypted and saved to disk\n");

    fis = new FileInputStream("cipherTest.out");

    byte[] decrypted = new byte[dataInputSize];
    read(decrypted, fis);

    fis.close();
    String decryptedAsString = new String(decrypted);

    System.out.println("DECRYPTED FILE:\n" + decryptedAsString + "\n");

}

From source file:MainClass.java

public static void main(String[] args) {

    try {/*from   w ww  .  ja va 2s . c om*/
        String FILE = "c:\\systemin.txt";
        FileOutputStream outStr = new FileOutputStream(FILE, true);
        PrintStream printStream = new PrintStream(outStr);

        System.setErr(printStream);

        Timestamp now = new Timestamp(System.currentTimeMillis());
        System.out.println(now.toString() + ": This is text that should go to the file");

        outStr.close();
        printStream.close();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        System.exit(-1);
    } catch (IOException ex) {
        ex.printStackTrace();
        System.exit(-1);
    }
}

From source file:BasApp.java

public static void main(String[] args) throws Exception {
    Options options = getOptions();/*from   w w  w.j  a  v  a2  s  . c  om*/
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        showHelp(options);
        return; // only show help and exit
    }

    final VOConfig cfg;
    if (cmd.hasOption("config")) {
        Serializer serializer = new Persister();
        final String config = cmd.getOptionValue("config");
        FileInputStream fis = new FileInputStream(config);
        cfg = serializer.read(VOConfig.class, fis);
        fis.close();
    } else {
        cfg = new VOConfig();
    }

    cfg.setCmd(cmd);

    CipherProvider dataCipherProvider = new CipherProvider();
    dataCipherProvider.setPassword(cmd.getOptionValue("passwd", null));
    CipherProvider metaCipherProvider = new CipherProvider();
    metaCipherProvider.setPassword(cmd.getOptionValue("passwd-meta", null));

    String repoPathStr = cfg.getRepository();
    Repository repository = new Repository(repoPathStr, dataCipherProvider, metaCipherProvider);

    if (cmd.hasOption("dump-config")) {
        Serializer serializer = new Persister();
        final FileOutputStream fos = new FileOutputStream(cmd.getOptionValue("dump-config"));
        serializer.write(cfg, fos);
        fos.close();
    }

    if (cmd.hasOption("backup")) {
        BackupService backup = new BackupService(cfg, repository);
        backup.run();
    }

    if (cmd.hasOption("restore")) {
        //noinspection unchecked
        String restoreTo = null;
        if (cmd.hasOption("restore-to")) {
            restoreTo = cmd.getOptionValue("restore-to");
        }

        RestoreService restore = new RestoreService(cmd.getOptionValue("r"), repository, cmd.getArgList(),
                restoreTo);
        restore.run();
    }

    if (cmd.hasOption("check")) {
        CheckService check = new CheckService(cmd.getOptionValue("check"), repository);
        check.run();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);

    Graphics g = img.getGraphics();
    g.setColor(Color.red);//from w ww .j a v a  2s .  co  m
    g.setFont(new Font("Arial", Font.BOLD, 14));
    g.drawString("Reference", 10, 80);

    int w = 100;
    int h = 100;
    int x = 1;
    int y = 1;

    int[] pixels = new int[w * h];
    PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);

    pg.grabPixels();
    BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

    for (int j = 0; j < h; j++) {
        for (int i = 0; i < w; i++) {
            bimg.setRGB(x + i, y + j, pixels[j * w + i]);
        }
    }

    FileOutputStream fout = new FileOutputStream("jpg.jpg");

    JPEGImageEncoder jencoder = JPEGCodec.createJPEGEncoder(fout);
    JPEGEncodeParam enParam = jencoder.getDefaultJPEGEncodeParam(bimg);

    enParam.setQuality(1.0F, true);
    jencoder.setJPEGEncodeParam(enParam);
    jencoder.encode(bimg);

    fout.close();

}

From source file:Main.java

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

    FileInputStream fin = null;/*from w  ww. j ava2  s. c om*/
    FileOutputStream fout = null;

    File file = new File("C:/myfile1.txt");

    fin = new FileInputStream(file);
    fout = new FileOutputStream("C:/myfile2.txt");

    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fin.read(buffer)) > 0) {
        fout.write(buffer, 0, bytesRead);
    }
    fin.close();
    fout.close();
}

From source file:com.ctriposs.rest4j.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    final CommandLineParser parser = new GnuParser();
    CommandLine cl = null;/* ww  w .j  a v  a2  s . c o  m*/
    try {
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": "
                        + schemaParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            fout.write(filteredSchema.toString().getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:Main.java

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

    byte b = 66;/*from  ww w .  j a  v a2  s .c  om*/
    int i = 0;
    FileOutputStream fos = new FileOutputStream(FileDescriptor.out);

    fos.write(b);

    fos.flush();

    FileInputStream fis = new FileInputStream("C://test.txt");

    // read till the end of the file
    while ((i = fis.read()) != -1) {
        // convert integer to character
        char c = (char) i;

        System.out.print(c);
    }
    fos.close();
    fis.close();
}

From source file:com.graphhopper.tools.Bzip2.java

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        throw new IllegalArgumentException("You need to specify the bz2 file!");
    }//  w w w .  java 2  s .co m

    String fromFile = args[0];
    if (!fromFile.endsWith(".bz2")) {
        throw new IllegalArgumentException("You need to specify a bz2 file! But was:" + fromFile);
    }
    String toFile = Helper.pruneFileEnd(fromFile);

    FileInputStream in = new FileInputStream(fromFile);
    FileOutputStream out = new FileOutputStream(toFile);
    BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);
    try {
        final byte[] buffer = new byte[1024 * 8];
        int n = 0;
        while (-1 != (n = bzIn.read(buffer))) {
            out.write(buffer, 0, n);
        }
    } finally {
        out.close();
        bzIn.close();
    }
}

From source file:StreamOneFour.java

public static void main(String args[]) throws Exception {
    String infile = "StreamOneFour.java";
    DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
    String mimeType = DocFlavor.INPUT_STREAM.POSTSCRIPT.getMimeType();
    StreamPrintServiceFactory[] factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,
            mimeType);/*from  ww w . ja v  a 2  s .c  o  m*/
    String filename = "out.ps";
    FileOutputStream fos = new FileOutputStream(filename);
    StreamPrintService sps = factories[0].getPrintService(fos);

    FileInputStream fis = new FileInputStream(infile);
    DocPrintJob dpj = sps.createPrintJob();
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    Doc doc = new SimpleDoc(fis, flavor, null);
    dpj.print(doc, pras);
    fos.close();
}