Skip to main content

Posts

Showing posts with the label Files n Streams

How to Upload a File and How to Store it using Java Program?

A quick and dirty Java Sockets API program:   // imports java.net.Socket, java.io.* void uploadFile(String hostAddr, int port, String fileName) throws FileNotFoundException, IOException { byte[] buf = new byte[1000]; int len = -1; // connect to host at hostAddr, port Socket sock = new Socket(hostAddr, port); FileInputStream in = new FileInputStream(fileName); OutputStream out = sock.getOutputStream(); while ( ( len = in.read(buf) ) != -1 ) { out.write(buf, 0, len); out.flush(); // manually flush output stream for sockets } out.close(); sock.close(); in.close(); } Author: Paul-John A.

How To Read/Write Excel Sheet with Java Program

There are two good choices for reading & writing Microsoft Excel Spreadsheet files from Java, in a platform independent way, - jexcelapi and Jakarta POI (HSSF). Both of them provide nice interface to access Excel data structure and even generate new spreadsheet. I have done extensive tests with both of them for a high-profile project for a Fortune 500 company. Previously also I had successfully used HSSF for another high profile client. In the paragraphs below I present my conclusions and sample code for reading Excel spreadsheet from Java using both the libraries. Comparison of JExcelAPI with Jakarta-POI (HSSF) 1. JExcelAPI is clearly not suitable for important data. It fails to read several files. Even when it reads it fails on cells for unknown reasons. In short JExcelAPI isnt suitable for enterprise use. 2. HSSF is the POI Projects pure Java implementation of the Excel  97(-2002) file format. It is a mature product and was able to correctly and effortlessly read excel...

How to List Files and Subdirectories in a Directory?

-- Here an example uses File class to retrive all files and subdirectories under the root. public static void main(String[] argv){ File dir = new File("c:\\"); String[] children = dir.list(); if (children != null) { for (String filename: children) { out.println(filename); } } else { out.println("No File Found."); } } Here is an example showing how to return subdirectories only. From java.io.File Java API doc, a list of files can also be retrieved as array of File objects. class DirectoryFileFilter implements FileFilter { public boolean accept(File file) { return file.isDirectory(); } }

How to Append Data to the End of Existing File in Java?

-- It's often useful to be able to append data to an existing file rather than overwriting it. The BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.The FileWriter is a convenience class used for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. Also, the FileWriter supports to append data to existing file. For example, class FileAppending { public static void main(String args[]) { try{ FileWriter fstream = new FileWriter("x.txt",true); BufferedWriter fbw = new BufferedWriter(fstream); fbw.write("append txt..."); fbw.newLine(); fbw.close(); }catch (Exception e) { System.out.println("Error: " + e.getMessage())...

How to read input from console (keyboard) in Java?

There are few ways to read input string from  your console/keyboard. The following smaple code shows how to read a string from the console/keyboard by using Java. public class ConsoleReadingDemo {     public static void main(String[] args) {         // ====         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));         System.out.print("Please enter user name : ");         String username = null;         try {             username = reader.readLine();         } catch (IOException e) {             e.printStackTrace();         }      ...

Files, Streams, I/O (Java.io)

Deleting a Directory (new File("directoryName")).delete(); Creating a Temporary File try { // Create temp file. File temp = File.createTempFile( "pattern", ".suffix"); // Delete temp file when program exits . temp.deleteOnExit(); // Write to temp file BufferedWriter out = new BufferedWriter( new FileWriter(temp)); out.write("aString"); out.close(); } catch (IOException e) { } Using a Random Access File try { File f = new File("filename"); RandomAccessFile raf = new RandomAccessFile(f, "rw"); // Read a character. char ch = raf.readChar(); // Seek to end of file. raf.seek(f.length()); // Append to the end. raf.writeChars("aString"); raf.close(); } catch (IOException e) { } Serializing an Object The object to be serialized must implement java.io.Serializable. try { ObjectOutput out = new ObjectOutputStream( new FileOutputStream("filename.ser")); out.writeObject(...

Simple Codings in Files & Streams(java.io.*)

Constructing a Path On Windows, this example creates the path \blash a\blash b. On Unix, the path would be /a/b. String path = File.separator + "a" + File.separator + "b" ; Reading Text from Standard Input try { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String str = ""; while (str != null) { System.out.print( "> prompt " ); str = in.readLine(); process (str); } } catch (IOException e) { } Reading Text from a File try { BufferedReader in = new BufferedReader( new FileReader( "infilename" )); String str; while ((str = in.readLine()) != null) { process (str); } in.close(); } catch (IOException e) { } Writing to a File If the file does not already exist, it is automatically created. try { BufferedWriter out = new BufferedWriter( new FileWriter( "outfilename" )); out.write( "aString" ); out.close(); } catch (IOException e) { } Creating a Directory (...

Simple Program for Reading Writing Content From File

Program for reading content from file: import java.io.*; public class MyFirstFilereadingApp { // Main method public static void main (String args[]) { // Stream to read file FileInputStream fin; try { // Open an input stream fin = new FileInputStream ("c:\\myfile1.txt"); // Read a line of text System.out.println( new DataInputStream(fin).readLine() ); // Close our input stream fin.close(); } // Catches any error conditions catch (IOException e) { System.err.println ("Unable to read fr! om file"); System.exit(-1); } } } Program for writing content from file: import java.io.*; public class MyFirstFileWritingApp { // Main method public static void main (String args[]) { // Stream to write file FileOutputStream fout; try { // Open an output stream fout = new FileOutputStream ("c:\\myfile1.txt"); // Print a line of text new PrintStream(fout).println ("hello ...