Example usage for java.io FileInputStream read

List of usage examples for java.io FileInputStream read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:info.reborncraft.ImageManipulation.java

/**
 * @param args/*from   w  w w.j a v  a 2s . c om*/
 */
public static void main(String[] args) {
    File file = new File("server-icon.png");

    try {
        /*
         * Reading a Image file from file system
         */
        FileInputStream imageInFile = new FileInputStream(file);
        byte imageData[] = new byte[(int) file.length()];
        imageInFile.read(imageData);
        imageInFile.close();
        /*
         * Converting Image byte array into Base64 String
         */
        String imageDataString = encodeImage(imageData);

        System.out.println(imageDataString);
    } catch (FileNotFoundException e) {
        System.out.println("Image not found" + e);
    } catch (IOException ioe) {
        System.out.println("Exception while reading the Image " + ioe);
    }

}

From source file:controller.tempClass.java

/**
 * @desc Image manipulation - Conversion
 *
 * @filename ImageManipulation.java//from   www .j  a va  2s .c  o  m
 * @author Jeevanandam M. (jeeva@myjeeva.com)
 * @copyright myjeeva.com
 */
public static void main(String[] args) {

    File file = new File("E:\\Photograph\\Temporary\\mshien.jpg");

    try {
        // Reading a Image file from file system
        FileInputStream imageInFile = new FileInputStream(file);
        byte imageData[] = new byte[(int) file.length()];
        imageInFile.read(imageData);

        // Converting Image byte array into Base64 String
        System.out.println(encodeImage(imageData));
        String imageDataString = encodeImage(imageData);

        // Converting a Base64 String into Image byte array
        byte[] imageByteArray = decodeImage(imageDataString);

        // Write a image byte array into file system
        FileOutputStream imageOutFile = new FileOutputStream("C:\\Users\\doanvanthien\\Desktop\\LOGO.png");

        imageOutFile.write(imageByteArray);

        imageInFile.close();
        imageOutFile.close();

        System.out.println("Image Successfully Manipulated!");
    } catch (FileNotFoundException e) {
        System.out.println("Image not found" + e);
    } catch (IOException ioe) {
        System.out.println("Exception while reading the Image " + ioe);
    }
}

From source file:com.rabbitmq.examples.FileProducer.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("h", "uri", true, "AMQP URI"));
    options.addOption(new Option("p", "port", true, "broker port"));
    options.addOption(new Option("t", "type", true, "exchange type"));
    options.addOption(new Option("e", "exchange", true, "exchange name"));
    options.addOption(new Option("k", "routing-key", true, "routing key"));

    CommandLineParser parser = new GnuParser();

    try {//from  www. j  av  a 2  s  .co m
        CommandLine cmd = parser.parse(options, args);

        String uri = strArg(cmd, 'h', "amqp://localhost");
        String exchangeType = strArg(cmd, 't', "direct");
        String exchange = strArg(cmd, 'e', null);
        String routingKey = strArg(cmd, 'k', null);

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        if (exchange == null) {
            System.err.println("Please supply exchange name to send to (-e)");
            System.exit(2);
        }
        if (routingKey == null) {
            System.err.println("Please supply routing key to send to (-k)");
            System.exit(2);
        }
        ch.exchangeDeclare(exchange, exchangeType);

        for (String filename : cmd.getArgs()) {
            System.out.print("Sending " + filename + "...");
            File f = new File(filename);
            FileInputStream i = new FileInputStream(f);
            byte[] body = new byte[(int) f.length()];
            i.read(body);
            i.close();

            Map<String, Object> headers = new HashMap<String, Object>();
            headers.put("filename", filename);
            headers.put("length", (int) f.length());
            BasicProperties props = new BasicProperties.Builder().headers(headers).build();
            ch.basicPublish(exchange, routingKey, props, body);
            System.out.println(" done.");
        }

        conn.close();
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Socket socket = new Socket("localhost", 8000);
    File file = new File("C:/Users/abc/Desktop/image.jpg");
    FileInputStream fileInputStream = new FileInputStream(file);

    byte[] fileBytes = new byte[(int) file.length()];
    OutputStream outputStream = socket.getOutputStream();
    int content;//  w ww .  j a  va  2s. c o m
    while ((content = fileInputStream.read(fileBytes)) != -1) {
        outputStream.write(fileBytes, 0, (int) file.length());
    }

    System.out.println("file size is " + fileBytes.length);
    for (byte a : fileBytes) {
        System.out.println(a);
    }
    socket.close();
    fileInputStream.close();
}

From source file:com.sight.facialrecog.util.ImageManipulation.java

/**
 * @param args/*  www.j a v  a 2 s . c  o m*/
 */
public static void main(String[] args) {
    File file = new File("/home/sight/Pictures/imagetest/close.jpg");

    try {
        /*
         * Reading an Image file from file system
         */
        FileInputStream imageInFile = new FileInputStream(file);
        byte imageData[] = new byte[(int) file.length()];
        imageInFile.read(imageData);

        /*
         * Converting Image byte array into Base64 String
         */
        String imageDataString = encodeImage(imageData);
        System.out.println(imageDataString);

        /*
         * Converting a Base64 String into Image byte array
         */
        byte[] imageByteArray = decodeImage(imageDataString);

        /*
         * Write an image byte array into file system
         */
        FileOutputStream imageOutFile = new FileOutputStream(
                "/home/sight/Pictures/imagetest/close-after-convert.jpg");
        imageOutFile.write(imageByteArray);

        imageInFile.close();
        imageOutFile.close();

        System.out.println("Image Successfully Manipulated!");
    } catch (FileNotFoundException e) {
        System.out.println("Image not found" + e);
    } catch (IOException ioe) {
        System.out.println("Exception while reading the Image " + ioe);
    }

}

From source file:com.cisco.dvbu.ps.common.adapters.core.CisWsClient.java

public static void main(String[] args) throws Exception {
    if (args.length < 8) {
        System.err.println(/*from   www .  j  av  a 2s. c o  m*/
                "usage: java com.cisco.dvbu.ps.common.adapters.core.CisWsClient endpointName endpointMethod configXml requestXml host port user password <domain>");
        System.exit(1);
    }
    org.apache.log4j.BasicConfigurator.configure();
    // DEBUG, INFO, ERROR
    org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.DEBUG);
    String endpointName = args[0]; // "server"
    String endpointMethod = args[1]; // "getServerAttributes"
    String adapterConfigPath = args[2]; // E:\dev\Workspaces\PDToolGitTest\PDTool_poc\resources\config\6.2.0\cis_adapter_config.xml
    String requestXMLPath = args[3]; // path to request xml

    Properties props = new Properties();
    props.setProperty(AdapterConstants.ADAPTER_HOST, args[4]);
    props.setProperty(AdapterConstants.ADAPTER_PORT, args[5]);
    props.setProperty(AdapterConstants.ADAPTER_USER, args[6]);
    props.setProperty(AdapterConstants.ADAPTER_PSWD, args[7]);
    if (args.length == 9)
        props.setProperty(AdapterConstants.ADAPTER_DOMAIN, args[8]);

    // Read the request xml file
    FileInputStream input = new FileInputStream(requestXMLPath);
    byte[] fileData = new byte[input.available()];
    input.read(fileData);
    input.close();
    String requestXml = new String(fileData, "UTF-8");

    // Execute the CIS Web Service Client for an adapter configuration
    CisWsClient cisclient = new CisWsClient(props, adapterConfigPath);

    System.out.println("Request: " + requestXml);
    // String requestXml = "<?xml version=\"1.0\"?> <p1:ServerAttributeModule xmlns:p1=\"http://www.dvbu.cisco.com/ps/deploytool/modules\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.dvbu.cisco.com/ps/deploytool/modules file:///e:/dev/Workspaces/PDToolGitTest/PDToolModules/schema/PDToolModules.xsd\">     <!--Element serverAttribute, maxOccurs=unbounded-->     <serverAttribute>         <id>sa1</id>         <name>/server/event/generation/sessions/sessionLoginFail</name>         <type>UNKNOWN</type>         <!--Element value is optional-->         <value>string</value>         <!--Element valueArray is optional-->         <valueArray>             <!--Element item is optional, maxOccurs=unbounded-->             <item>string</item>             <item>string</item>             <item>string</item>         </valueArray>         <!--Element valueList is optional-->         <valueList>             <!--Element item is optional, maxOccurs=unbounded-->             <item>                 <!--Element type is optional-->                 <type>UNKNOWN</type>                 <!--Element value is optional-->                 <value>string</value>             </item>             <item>                 <!--Element type is optional-->                 <type>UNKNOWN</type>                 <!--Element value is optional-->                 <value>string</value>             </item>             <item>                 <!--Element type is optional-->                 <type>UNKNOWN</type>                 <!--Element value is optional-->                 <value>string</value>             </item>         </valueList>         <!--Element valueMap is optional-->         <valueMap>             <!--Element entry is optional, maxOccurs=unbounded-->             <entry>                 <!--Element key is optional-->                 <key>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </key>                 <!--Element value is optional-->                 <value>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </value>             </entry>             <entry>                 <!--Element key is optional-->                 <key>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </key>                 <!--Element value is optional-->                 <value>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </value>             </entry>             <entry>                 <!--Element key is optional-->                 <key>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </key>                 <!--Element value is optional-->                 <value>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </value>             </entry>         </valueMap>     </serverAttribute> </p1:ServerAttributeModule>";
    String response = cisclient.sendRequest(endpointName, endpointMethod, requestXml);
    System.out.println("Response: " + response);
}

From source file:Main.java

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

    FileInputStream fin = null;
    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);
    }/*from   www .  j  a v  a  2  s .c o m*/
    fin.close();
    fout.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    FileInputStream inStream = new FileInputStream("test.txt");
    ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream("compressed.zip"));

    outStream.putNextEntry(new ZipEntry("test.txt"));

    byte[] buffer = new byte[1024];
    int bytesRead;

    while ((bytesRead = inStream.read(buffer)) > 0) {
        outStream.write(buffer, 0, bytesRead);
    }//w  ww.  j  av  a2 s. c  o  m

    outStream.closeEntry();
    outStream.close();
    inStream.close();
}

From source file:Blobs.java

public static void main(String args[]) {
    if (args.length != 1) {
        System.err.println("Syntax: <java Blobs [driver] [url] " + "[uid] [pass] [file]");
        return;/*from   w w w  .  ja  va2s . c  o  m*/
    }
    try {
        Class.forName(args[0]).newInstance();
        Connection con = DriverManager.getConnection(args[1], args[2], args[3]);
        File f = new File(args[4]);
        PreparedStatement stmt;

        if (!f.exists()) {
            // if the file does not exist
            // retrieve it from the database and write it to the named file
            ResultSet rs;

            stmt = con.prepareStatement("SELECT blobData " + "FROM BlobTest " + "WHERE fileName = ?");

            stmt.setString(1, args[0]);
            rs = stmt.executeQuery();
            if (!rs.next()) {
                System.out.println("No such file stored.");
            } else {
                Blob b = rs.getBlob(1);
                BufferedOutputStream os;

                os = new BufferedOutputStream(new FileOutputStream(f));
                os.write(b.getBytes(0, (int) b.length()), 0, (int) b.length());
                os.flush();
                os.close();
            }
        } else {
            // otherwise read it and save it to the database
            FileInputStream fis = new FileInputStream(f);
            byte[] tmp = new byte[1024];
            byte[] data = null;
            int sz, len = 0;

            while ((sz = fis.read(tmp)) != -1) {
                if (data == null) {
                    len = sz;
                    data = tmp;
                } else {
                    byte[] narr;
                    int nlen;

                    nlen = len + sz;
                    narr = new byte[nlen];
                    System.arraycopy(data, 0, narr, 0, len);
                    System.arraycopy(tmp, 0, narr, len, sz);
                    data = narr;
                    len = nlen;
                }
            }
            if (len != data.length) {
                byte[] narr = new byte[len];

                System.arraycopy(data, 0, narr, 0, len);
                data = narr;
            }
            stmt = con.prepareStatement("INSERT INTO BlobTest(fileName, " + "blobData) VALUES(?, ?)");
            stmt.setString(1, args[0]);
            stmt.setObject(2, data);
            stmt.executeUpdate();
            f.delete();
        }
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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);
    write(inputBytes, fos);/*from w  w w.j  a  v a2s .co m*/
    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");

}