Example usage for java.io File length

List of usage examples for java.io File length

Introduction

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

Prototype

public long length() 

Source Link

Document

Returns the length of the file denoted by this abstract pathname.

Usage

From source file:UDPSend.java

public static void main(String args[]) {
    try {/*from www .  j  ava2s  . co  m*/
        // Check the number of arguments
        if (args.length < 3)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the arguments
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Figure out the message to send.
        // If the third argument is -f, then send the contents of the file
        // specified as the fourth argument. Otherwise, concatenate the
        // third and all remaining arguments and send that.
        byte[] message;
        if (args[2].equals("-f")) {
            File f = new File(args[3]);
            int len = (int) f.length(); // figure out how big the file is
            message = new byte[len]; // create a buffer big enough
            FileInputStream in = new FileInputStream(f);
            int bytes_read = 0, n;
            do { // loop until we've read it all
                n = in.read(message, bytes_read, len - bytes_read);
                bytes_read += n;
            } while ((bytes_read < len) && (n != -1));
        } else { // Otherwise, just combine all the remaining arguments.
            String msg = args[2];
            for (int i = 3; i < args.length; i++)
                msg += " " + args[i];
            // Convert the message to bytes using UTF-8 encoding
            message = msg.getBytes("UTF-8");
        }

        // Get the internet address of the specified host
        InetAddress address = InetAddress.getByName(host);

        // Initialize a datagram packet with data and address
        DatagramPacket packet = new DatagramPacket(message, message.length, address, port);

        // Create a datagram socket, send the packet through it, close it.
        DatagramSocket dsocket = new DatagramSocket();
        dsocket.send(packet);
        dsocket.close();
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (Id int, b BLOB);");

    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO survey VALUES(1,?)");

    File file = new File("blob.txt");
    FileInputStream fis = new FileInputStream(file);
    pstmt.setBinaryStream(1, fis, (int) file.length());
    pstmt.execute();/*from ww  w  .ja  v  a  2  s  .co m*/

    fis.close();
    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(url, username, password);
    conn.setAutoCommit(false);//  w  w  w. j a  v  a 2 s  .  co m

    String sql = "INSERT INTO pictures (name, description, image) VALUES (?, ?, ?)";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setString(1, "java.gif");
    stmt.setString(2, "Java Official Logo");

    File image = new File("D:\\a.gif");
    FileInputStream fis = new FileInputStream(image);
    stmt.setBinaryStream(3, fis, (int) image.length());
    stmt.execute();

    conn.commit();
    fis.close();
    conn.close();
}

From source file:config.MainClass.java

/**
 * @param args the command line arguments
 *//*from   w w w.  ja va  2  s.c  om*/
public static void main(String[] args) {
    // TODO code application logic here
    File file = new File("D:\\iti images\\Dish Party_6-11-2014\\IMG_5376.jpg");
    byte[] bFile = new byte[(int) file.length()];

    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        //convert file into array of bytes
        fileInputStream.read(bFile);
        fileInputStream.close();
    } catch (Exception e) {
        System.out.println("Error in reading the image");
    }
    UserData data = new UserData();
    data.setUserName("hasby allah");
    data.setBirthday(new Date());
    data.setPhone("65656");
    data.setFullName("7asby allah w n3m el wakel");
    data.setAddress("haram");
    data.setPassword("password");
    data.setImage(bFile);
    AbstractApplicationContext fact = new ClassPathXmlApplicationContext("SpringConfig.xml");
    DaoService serviceInterface = fact.getBean(DaoService.class);
    serviceInterface.save(data);
}

From source file:Main.java

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

    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(url, username, password);
    conn.setAutoCommit(false);//from  w  ww.  ja v  a 2s  . co  m

    String sql = "INSERT INTO documents (name, description, data) VALUES (?, ?, ?)";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setString(1, "a.txt");
    stmt.setString(2, "b");

    File data = new File("C:\\a.txt");
    FileReader reader = new FileReader(data);
    stmt.setCharacterStream(3, reader, (int) data.length());
    stmt.execute();

    conn.commit();
    reader.close();
    conn.close();

}

From source file:FileList.java

public static void main(String[] args) {
    final int assumedLineLength = 50;
    File file = new File(args[0]);
    List<String> fileList = new ArrayList<String>((int) (file.length() / assumedLineLength) * 2);
    BufferedReader reader = null;
    int lineCount = 0;
    try {//from  www .  j  ava  2 s  .com
        reader = new BufferedReader(new FileReader(file));
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            fileList.add(line);
            lineCount++;
        }
    } catch (IOException e) {
        System.err.format("Could not read %s: %s%n", file, e);
        System.exit(1);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
    int repeats = Integer.parseInt(args[1]);
    Random random = new Random();
    for (int i = 0; i < repeats; i++) {
        System.out.format("%d: %s%n", i, fileList.get(random.nextInt(lineCount - 1)));
    }
}

From source file:com.boonya.http.async.examples.nio.client.ZeroCopyHttpExchange.java

public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {/*w  w  w  . ja va2s  . c  o m*/
        httpclient.start();
        File upload = new File(args[0]);
        File download = new File(args[1]);
        ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload,
                ContentType.create("text/plain"));
        ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) {

            @Override
            protected File process(final HttpResponse response, final File file, final ContentType contentType)
                    throws Exception {
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    throw new ClientProtocolException("Upload failed: " + response.getStatusLine());
                }
                return file;
            }

        };
        Future<File> future = httpclient.execute(httpost, consumer, null);
        File result = future.get();
        System.out.println("Response file length: " + result.length());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:Main.java

  public static void main(String[] args) throws IOException {
  ServerSocket servsock = new ServerSocket(123456);
  File myFile = new File("s.pdf");
  while (true) {//from ww  w .jav  a 2  s  .  com
    Socket sock = servsock.accept();
    byte[] mybytearray = new byte[(int) myFile.length()];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
    bis.read(mybytearray, 0, mybytearray.length);
    OutputStream os = sock.getOutputStream();
    os.write(mybytearray, 0, mybytearray.length);
    os.flush();
    sock.close();
  }
}

From source file:httpasync.ZeroCopyHttpExchange.java

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

    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {//  w  w w  .  j  ava 2  s .c  om
        httpclient.start();
        File upload = new File(args[0]);
        File download = new File(args[1]);
        ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload,
                ContentType.create("text/plain"));
        ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) {

            @Override
            protected File process(final HttpResponse response, final File file, final ContentType contentType)
                    throws Exception {
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    throw new ClientProtocolException("Upload failed: " + response.getStatusLine());
                }
                return file;
            }

        };
        Future<File> future = httpclient.execute(httpost, consumer, null);
        File result = future.get();
        System.out.println("Response file length: " + result.length());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (Id int, b CLOB);");

    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO survey VALUES(1,?)");

    File file = new File("c:/Java_Dev/data.txt");
    FileInputStream fis = new FileInputStream(file);
    pstmt.setAsciiStream(1, fis, (int) file.length());
    pstmt.execute();/*  w  w  w . ja  v a 2s.  c om*/

    fis.close();
    st.close();
    conn.close();
}