Transfer a file via Socket

A client module connects to a server then a file is sent to the client. This exemple is very simple with no authentication and hard-coded filename!

First a server module.


import java.net.*;
import java.io.*;

public class FileServer {
public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");

Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);

// sendfile
File myFile = new File ("source.pdf");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
}

The client module


import java.net.*;
import java.io.*;

public class FileClient{
public static void main (String [] args ) throws IOException {
int filesize=6022386; // filesize temporary hardcoded

long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket("127.0.0.1",13267);
System.out.println("Connecting...");

// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("source-copy.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;

// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
}
}

Create/Delete Directory ,File

In the section of Java Tutorial you will learn how to create directory using java program. This program also explains the process of creating all non-existent ancestor directories automatically. We will use the class File class to crate the directory.

Class File
The File class an abstract representation of file and directory pathnames. File class is used to interact with the files system.

Here is the code for creating directory and all non-existing ancestor directories:


import java.io.*;
class CreateDirectory
{
public static void main(String args[])
{
try{
String strDirectoy ="test";
String strManyDirectories="dir1/dir2/dir3";

// Create one directory
boolean success = (new File(strDirectoy)).mkdir();
if (success) {
System.out.println("Directory: " + strDirectoy + " created");
}

// Create multiple directories
success = (new File(strManyDirectories)).mkdirs();
if (success) {
System.out.println("Directories: " + strManyDirectories + " created");
}

}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

This example illustrates how to delete the specified file or directory after checking weather the file exists or not. This topic is related to the I/O (input/output) of java.io package.

In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames.

Explanation

This program deletes the specified file if that exists. We will be declaring a function called deletefile which deletes the specified directory or file.

deletefile(String file)

The function deletefile(String file) takes file name as parameter. The function creates a new File instance for the file name passed as parameter

File f1 = new File(file);

and delete the file using delete function f1.delete(); which return the Boolean value (true/false). It returns true if and only if the file or directory is successfully deleted; false otherwise.

delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

Returns:
true if and only if the file or directory is successfully deleted; false otherwise

Code of the Program :


import java.io.*;

public class DeleteFile{
private static void deletefile(String file){
File f1 = new File(file);
boolean success = f1.delete();
if (!success){
System.out.println("Deletion failed.");
System.exit(0);
}else{
System.out.println("File deleted.");
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("File has not mentioned.");
System.exit(0);
case 1: deletefile(args[0]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}

Java – Copying one file to another

Objective:to copy contents from one file to another file. This topic is related to the I/O (input/output) of java.io package.

In this example we are using File class of java.io package. The File class is an abstract representation of file and directory pathnames. This class is an abstract, system-independent view of hierarchical pathnames. An abstract pathname has two components:

1. An optional system-dependent prefix string,
such as a disk-drive specifier, “/” for the UNIX root directory, or “\\” for a Win32 UNC pathname, and
2. A sequence of zero or more string names.

Explanation

This program copies one file to another file. We will be declaring a function called copyfile which copies the contents from one specified file to another specified file.

copyfile(String srFile, String dtFile)

The function copyfile(String srFile, String dtFile) takes both file name as parameter. The function creates a new File instance for the file name passed as parameter

File f1 = new File(srFile);
File f2 = new File(dtFile);

and creates another InputStream instance for the input object and OutputStream instance for the output object passed as parameter

InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);

and then create a byte type buffer for buffering the contents of one file and write to another specified file from the first one specified file.

// For creating a byte type buffer
byte[] buf = new byte[1024];
// For writing to another specified file from buffer buf
out.write(buf, 0, len);

Code of the Program :


import java.io.*;

public class CopyFile{
private static void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

//For Append the file.
// OutputStream out = new FileOutputStream(f2,true);

//For Overwrite the file.
OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("File has not mentioned.");
System.exit(0);
case 1: System.out.println("Destination file has not mentioned.");
System.exit(0);
case 2: copyfile(args[0],args[1]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}

Java Write To File

Objective: to write java program to write to a file. We will use the class FileWriter and BufferedWriter to write to a file.

Class FileWriter:

The FileWriter is a 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. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

BufferedWriter:

The BufferWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Here is the code of java program to write text to a file:


import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

Print pdf


package javaprint;

import javax.print.*;
import javax.print.attribute.*;

import java.io.*;
import java.util.*;

/**
* Title: PrintPdf.java
* Description: This class converts a PDF format document into PostScript (ps) and prints the same.
* Copyright: Copyright (c) 2003
* Company: Misys Healthcare Systems
* @author Madhusudan M Krishnamurthy
* @e-mail madhusudan dot krishnamurthy at misyshealthcare dot com
* @version 1.0
*/

public class PrintPdf
{
/* Input PDF file name */
private String inputFileName;

/* Autogenerated output PS file name */
private String outputFileName;

/* Path from where the pdftops tool can be accessed */
private static final String PDF_TO_PS_TOOL_PATH = "C:\\pdftops";

/* Thread class which clean up accumulates .ps file every 1 hour. */
private CleanUpThread cleanUpThread;

/**
* Default Constructor.
*/
public PrintPdf()
{
cleanUpThread = new CleanUpThread();
}

/**
* Constructor, the PDF file to be printed should be passed as parameter to this.
*/
public PrintPdf(String inputFileName)
{
this.inputFileName = inputFileName;
cleanUpThread = new CleanUpThread();
}

/**
* Sets the inputFileName property value
* @param inputFileName
*/
public void setInputFileName(String inputFileName)
{
this.inputFileName = inputFileName;
}

/**
* Accessor method to obtain the value of inputFileName property value.
* @return java.lang.String (inputFileName).
*/
public String getInputFileName()
{
return this.inputFileName;
}

/**
* Sets the outputFileName property value.
* This method sets the generated PostScript file name that is generated for the input PDF file name.
* @param outputFileName
*/
private void setOuputFileName(String outputFileName)
{
this.outputFileName = outputFileName;
}

/**
* Accessor method to obtain the outputFileName name.
* @return outputFileName
*/
public String getOutputFileName()
{
return this.outputFileName;
}

/**
* Core logic to print the input document.
*/
public void printDocument()
{
try
{
generateOuputFileName();
convertPdfToPostScript();

PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
PrintService printPrintService = null;
PrintService service = ServiceUI.printDialog(null, 200, 200,printService, defaultService, flavor, pras);
if (service != null)
{
DocPrintJob job = service.createPrintJob();
FileInputStream fis = new FileInputStream(getOutputFileName());
DocAttributeSet das = new HashDocAttributeSet();
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* This method generates the post script output file name. The method obtains the path and PDF fileName and generates
* the post script file name with the same name as PDF file under the same path.
*/
protected void generateOuputFileName()
{
try
{
File file = new File(getInputFileName()); //Create a File Object from the give PDF file.
String filename = file.getName();
String parent = file.getParent();
StringTokenizer fileNameTokenizer = new StringTokenizer(filename, ".");
filename = fileNameTokenizer.nextToken(); //Extrace the file name except the extension. ex: if file name is 'xxx.pdf' this code will return 'xxx'

// this will result in a value as, "C:\" + "\" + "xxx" + "1028393030" + ".ps"; The file name generated is concatinated with current date
// time to make it unique, may be there will be situation where two clients may be generating the print output to the same PDF file.
filename = parent + filename + ((new Date()).getTime()) + ".ps";
setOuputFileName(filename);
}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* This method convets the given PDF file to PS file
* This method uses the pdftopdf.exe tool to pass the input pdf file name and output ps file name to
* generate the Postscript version of the input PDF file.
*/
protected void convertPdfToPostScript()
{
try
{
Runtime runTime = Runtime.getRuntime();
Process process = null;
String command = PDF_TO_PS_TOOL_PATH + " " + getInputFileName() + " " + getOutputFileName();
process = runTime.exec(command);
}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* This method cleans up the generated post script document so that all the generated PS documents
* clog the hard drive space.
*/
protected synchronized void cleanUpPSDocument()
{
try
{
File file = new File(getOutputFileName());
file = new File(file.getParent());
File[] fileList = file.listFiles(
new FilenameFilter ()
{
public boolean accept(File dir, String name)
{
if (name.endsWith(".ps"))
return true;
else
return false;
}
}
);
if (fileList != null)
{
for (int i = 0; i (60 * 60 * 1000)) // If the file is more than ONE hour old then delete it.
fileList.delete();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* Title:
* Description: This private inner class is used to clean up the converted ps file. Over a period of time
* the files PS file gets accumulated and clogs the hard disk space hence every one hour clean the files.
* Copyright: Copyright (c) 2003
* Company: Misys Healthcare Systems
* @author Madhusudan M Krishnamurthy
* @e-mail madhusudan dot krishnamurthy at misyshealthcare dot com
* @version 1.0
*/
private class CleanUpThread extends Thread
{
public CleanUpThread()
{
start();
}

public void run()
{
while(true)
{
cleanUpPSDocument();
try
{
sleep(60 * 60 * 1000); //Sleep for ONE hour
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}

/**
* Test Harness
*/
public static void main(String args[]) //throws Exception
{
PrintPdf printPdf = new PrintPdf("C:\\IBMJavaPrint.pdf");
printPdf.printDocument();
}
}