RandomAccessFile.writeUTF(String)
Hallo,
I have some problem with the method RandomAccessFile.writeUTF(String).
It writes a Character into the File and I don't know why.
I have to use the RandomAccessFile because I had to set the position of the FilePointer.
Here is the Testclass
public class UserFile
public static void main(String[] args)
try
new UserFile().writeToFile();
catch (IOException ioe)
ioe.printStackTrace();
}// end of main()
private void writeToFile() throws IOException
String sep = System.getProperty("line.separator");
String kommentar = "This is a Comment";
String user = "12.34.56.789";
File dataFile = new File("user.dat");
RandomAccessFile random = new RandomAccessFile(dataFile,"rw");
random.seek(dataFile.length());
String s = sep+"\\\\"+kommentar+sep+user;
random.writeUTF(s);
random.close();
}// end of writeToFile()
}// end of classthe output is:
\\This is a Comment
12.34.56.789
the '#' Symbol is the char that I don't know where it comes from.
thank for your help
Hugo Balder
the RandomAccessFile.writeUTF(String) javadoc says:
"First, two bytes are written to the file, starting at the current file pointer, as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the UTF-8 encoding for each character."
so RTFM, it helps
Similar Messages
-
The constructor RandomAccessFile(File, String) is undefined
This is the compile error I got when trying to compile a solution from the Java Tutorials on sun.com
http://java.sun.com/docs/books/tutorial/essential/exceptions/QandE/answers.html
This is the entire class file:
import java.io.*;
public class catFile {
public static void cat(File file) {
RandomAccessFile input = null;
String line = null;
try {
input = new RandomAccessFile(file, "r");
while ((line = input.readLine()) != null) {
System.out.println(line);
return;
} catch(FileNotFoundException fnf) {
System.err.format("File: %s not found%n", file);
} catch(IOException e) {
System.err.println(e.toString());
} finally {
if (input != null) {
try {
input.close();
} catch(IOException io) {
}I included the java.io package as you can see and I still get this error:
"The constructor RandomAccessFile(File, String) is undefined" - line 9
I googled this error to no avail. Any ideas?Have you created your own class called RandomAccessFile? or File class?
-
RandomAccessFile on Server..Where is File Created?
Hello Professionals:
I have created an oracle trigger on a table during insert that passes the column contents to a java procedure that is intended to write this data to a RandomAccessFile. I am not sure where the file will be created on the Server. I created my java classes on an Oracle 8.1.6 database. My java class (and procedure) that writes the data to the file is indicated below. Your guidance is needed. Thanks.
Chris
package mypackage1;
import java.io.*;
public class AddData
public static void TriggerData(int v_id, String v_name)
Record blank;
String fileName = "TriggerData20.dat";
blank = new Record(v_id,v_name);
try {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
file.seek(file.length());
System.out.println("Just getting ready to write to file");
blank.write(file);
System.out.println("Just written data to file");
System.exit(0);
catch (IOException e){
System.out.println("This is not a valid file");
System.exit(1);
public static void main(String[] args)
AddRecord addRecord = new AddRecord();
// A class that represents one record of information.
package mypackage1;
import java.io.Serializable;
public class AccountRecord implements Serializable
private int account;
private String firstName;
public AccountRecord()
this(0,"");
public AccountRecord(int acct, String first)
setAccount(acct);
setFirstName(first);
public void setAccount(int acct)
account = acct;
public int getAccount(){return account;}
public void setFirstName(String first)
firstName = first;
public String getFirstName(){return firstName;}
//Record class for RandomAccessFile programs;
//This class will be wrapped as a procedure to call in the Oracle Trigger;
//Two or more values will be passed into the method call Record(xx,xx,etc) from the Oracle table;
package mypackage1;
import java.io.*;
//import AccountRecord class from package!!!!!!!!!!!!!!!!!
public class Record extends AccountRecord
//String file = "TriggerData5.dat";
public Record()
this(25,"farting");
public Record(int acct, String first)
super(acct,first);
//Read a record from the specified RandomAccessFile
setAccount(file.readInt() );
setFirstName(padName(file) );
private String padName(RandomAccessFile f) throws IOExeption
char name[] = new char [15], temp;
for (int i = 0; i < name.length; i++) {
temp = f.readChar();
name[i] = temp;
return new String(name).replace('\0',' ' );
//Write a record to the specified RandomAccessFile
public void write(RandomAccessFile file) throws IOException
//file.seek(size());
file.writeInt(getAccount() );
writeName(file, getFirstName() );
private void writeName(RandomAccessFile f, String name) throws IOException
StringBuffer buf = null;
if (name != null )
buf = new StringBuffer(name);
else
buf = new StringBuffer(15);
buf.setLength(15);
f.writeChars(buf.toString() );
/*//Not too sure if I need to have the main method here!!!!!!!!!!!!!!
public static void main(String[] args)
Record record = new Record();
}per OracleJVM development: the file will be created with a root of $ORACLE_HOME if the filename is not an absolute
path. The writer must have the proper permissions to write the file. All subdirectories, if any in the path name, must exist or an
exception will be thrown.
My guess is that they would get written into the user_dump_dest directory.
Probably a question that will be answered most quickly by the RDBMS forum,
or by a quick test on your database with a file with a well-known name. -
RandomAccessFile on Server.. Where is File Located???
Hello Professionals:
I have created an oracle trigger on a table on insert that passes the column contents to a java procedure that is intended to write this data to a RandomAccessFile. I am not sure where the file will be created on the Server. I created my java classes on an Oracle 8.1.6 database. My java class (and procedure) that writes the data to the file is indicated below. Your guidance is needed. Thanks. I am logged into the database as teh schema owner of the table and java classes.
Chris
package mypackage1;
import java.io.*;
public class AddData
public static void TriggerData(int v_id, String v_name)
Record blank;
String fileName = "TriggerData20.dat";
blank = new Record(v_id,v_name);
try {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
file.seek(file.length());
System.out.println("Just getting ready to write to file");
blank.write(file);
System.out.println("Just written data to file");
System.exit(0);
catch (IOException e){
System.out.println("This is not a valid file");
System.exit(1);
public static void main(String[] args)
AddRecord addRecord = new AddRecord();
// A class that represents one record of information.
package mypackage1;
import java.io.Serializable;
public class AccountRecord implements Serializable
private int account;
private String firstName;
public AccountRecord()
this(0,"");
public AccountRecord(int acct, String first)
setAccount(acct);
setFirstName(first);
public void setAccount(int acct)
account = acct;
public int getAccount(){return account;}
public void setFirstName(String first)
firstName = first;
public String getFirstName(){return firstName;}
//Record class for RandomAccessFile programs;
//This class will be wrapped as a procedure to call in the Oracle Trigger;
//Two or more values will be passed into the method call Record(xx,xx,etc) from the Oracle table;
package mypackage1;
import java.io.*;
//import AccountRecord class from package!!!!!!!!!!!!!!!!!
public class Record extends AccountRecord
//String file = "TriggerData5.dat";
public Record()
this(25,"farting");
public Record(int acct, String first)
super(acct,first);
//Read a record from the specified RandomAccessFile
setAccount(file.readInt() );
setFirstName(padName(file) );
private String padName(RandomAccessFile f) throws IOExeption
char name[] = new char [15], temp;
for (int i = 0; i < name.length; i++) {
temp = f.readChar();
name[i] = temp;
return new String(name).replace('\0',' ' );
//Write a record to the specified RandomAccessFile
public void write(RandomAccessFile file) throws IOException
//file.seek(size());
file.writeInt(getAccount() );
writeName(file, getFirstName() );
private void writeName(RandomAccessFile f, String name) throws IOException
StringBuffer buf = null;
if (name != null )
buf = new StringBuffer(name);
else
buf = new StringBuffer(15);
buf.setLength(15);
f.writeChars(buf.toString() );
/*//Not too sure if I need to have the main method here!!!!!!!!!!!!!!
public static void main(String[] args)
Record record = new Record();
}Chris,
i have posted a response on the JDeveloper forum which says:
The file will be created with a root of $ORACLE_HOME ifthe filename is not
an absolute path. The writer must have the proper permissions to write the
file. All subdirectories, if any in the path name, must exist or an
exception will be thrown.
Kuassi
Hello Professionals:
I have created an oracle trigger on a table on insert that passes the column contents to a java procedure that is intended to write this data to a RandomAccessFile. I am not sure where the file will be created on the Server. I created my java classes on an Oracle 8.1.6 database. My java class (and procedure) that writes the data to the file is indicated below. Your guidance is needed. Thanks. I am logged into the database as teh schema owner of the table and java classes.
Chris
package mypackage1;
import java.io.*;
public class AddData
public static void TriggerData(int v_id, String v_name)
Record blank;
String fileName = "TriggerData20.dat";
blank = new Record(v_id,v_name);
try {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
file.seek(file.length());
System.out.println("Just getting ready to write to file");
blank.write(file);
System.out.println("Just written data to file");
System.exit(0);
catch (IOException e){
System.out.println("This is not a valid file");
System.exit(1);
public static void main(String[] args)
AddRecord addRecord = new AddRecord();
// A class that represents one record of information.
package mypackage1;
import java.io.Serializable;
public class AccountRecord implements Serializable
private int account;
private String firstName;
public AccountRecord()
this(0,"");
public AccountRecord(int acct, String first)
setAccount(acct);
setFirstName(first);
public void setAccount(int acct)
account = acct;
public int getAccount(){return account;}
public void setFirstName(String first)
firstName = first;
public String getFirstName(){return firstName;}
//Record class for RandomAccessFile programs;
//This class will be wrapped as a procedure to call in the Oracle Trigger;
//Two or more values will be passed into the method call Record(xx,xx,etc) from the Oracle table;
package mypackage1;
import java.io.*;
//import AccountRecord class from package!!!!!!!!!!!!!!!!!
public class Record extends AccountRecord
//String file = "TriggerData5.dat";
public Record()
this(25,"farting");
public Record(int acct, String first)
super(acct,first);
//Read a record from the specified RandomAccessFile
setAccount(file.readInt() );
setFirstName(padName(file) );
private String padName(RandomAccessFile f) throws IOExeption
char name[] = new char [15], temp;
for (int i = 0; i < name.length; i++) {
temp = f.readChar();
name[i] = temp;
return new String(name).replace('\0',' ' );
//Write a record to the specified RandomAccessFile
public void write(RandomAccessFile file) throws IOException
//file.seek(size());
file.writeInt(getAccount() );
writeName(file, getFirstName() );
private void writeName(RandomAccessFile f, String name) throws IOException
StringBuffer buf = null;
if (name != null )
buf = new StringBuffer(name);
else
buf = new StringBuffer(15);
buf.setLength(15);
f.writeChars(buf.toString() );
/*//Not too sure if I need to have the main method here!!!!!!!!!!!!!!
public static void main(String[] args)
Record record = new Record(); -
According to Java doc,
writeUTF is
writeUTF(String str) actually
"Writes two bytes of length information to the output stream, followed by the Java modified UTF representation of every character in the string s"
However, when I read back using readUTF, there are some junk characters. The question is how to I extract the original data. I want to use substring but how do I know those "additional Junk" characters is one char or two char ???
thankThat means that when you use readUTF, you are reading something that wasn't written by writeUTF. You shouldn't get "junk" characters under normal circumstances, unless those "junk" characters were in the original string.
-
Limit on number of open RandomAccessFiles
I'm implementing a small database using J2SDK1.4 NIO FileChannel and MappedByteBuffer as follows:
FileChannel fc = new RandomAccessFile(dataFile, "rw").getChannel();
MappedByteBuffer mbb = fc.map (FileChannel.MapMode.READ_WRITE, 0L, (int) fc.size());My problem is that there is a certain limit on the maximum number of open files and the native method RandomAccessFile.open(String name, int mode) throws a FileNotFoundException with message:(Too many open files).
This limit is not system/platform dependent, I experienced the same exception on both NT and Linux machines. Is there a way to raise this limit?
My workaround now is to close the FileChannel immediately after having mapped it to ByteBuffer but then I can only read/write to the buffer and cannot append more data to the file.
All help will be greatly appreciated.I have the exact same problem. Any solutions please?
-
My FIle Throws EOFException....
Hi,
My program throws EOFException very. I can't find it .can you help me any one.This is my algoritham project. please help me.
This is my code.
import java.util.TreeMap;
import java.io.*;
import java.util.Iterator;
import java.util.StringTokenizer;
public class TableIndexSolution
private BufferedReader reader;
private RandomAccessFile raFile; //file to manipulated
private RandomAccessFile index;
public static void main(String[] args)
TableIndexSolution app = new TableIndexSolution();
app.init();
app.run();
private void init()
{ raFile = null;
reader = new BufferedReader(new InputStreamReader(System.in));
private void run()
{ // Continually read command from user in a loop and then do the requested query
String choice, sqlSt;
fileCreate();
printMenu();
choice = getLine();
while (!(choice.equals("X") || choice.equals("x")))
if (choice.equals("1"))
{// Read in and output entire raFile using API for class RandomAccessFile
readAll();
else if (choice.equals("2"))
{//Locate and output the record with the following key
System.out.print("Please enter the key to locate the record: ");
String key = getLine().trim(); //implemented below to read an integer from std.in
System.out.println(findRecord(key) );
else if (choice.equals("3"))
{// Prompt for a record to insert, then append to raFile
System.out.print("Enter the record:");
String record = getLine().trim();
insertRecord(record);
else if (choice.equals("4"))
{// prompt for key of record to delete
System.out.print("Please enter the key to locate the record to delete: ");
String key = getLine().trim();
deleteRecord( key);
else if (choice.equals("5"))
{//read in key value and call update method
System.out.print("Enter key of record to update: " );
String key = getLine();
System.out.print("Enter column number of field to update: ");
String column = getLine();
int col = Integer.parseInt(column);
System.out.print("Enter value of field to update: ");
String value = getLine();
updateRecord(key, col, value);
else if (choice.equals("6"))
readAllOrdered();
else if (choice.equals("7"))
System.out.print("Please enter the key to locate the record to find: ");
String key = getLine().trim();
//int keyValue = Integer.parseInt(key);
String keyValue = (String)key;
findRecordIndex(keyValue);
else if (choice.equals("C"))
createIndex();
else if (choice.equals("F"))
fileCreate();
else
System.out.println("Invalid input!");
printMenu();
choice = getLine();
try{
raFile.close();
if(index != null)
index.close();
reader.close();
catch(IOException io)
{System.out.println(io); }
/*H2*****************************************************************************
* createIndex() - creates a RandomAccessFile index to hold as bytes an integer index value
and an integer for the byte offset
private void createIndex()
long startTime = System.currentTimeMillis();
//create index file
try
index = new RandomAccessFile("index.dat", "rw" );
catch(FileNotFoundException fnf){System.out.println("File not found in this directory"); }
try
index.setLength(0); //create new index
index.seek(0);
raFile.seek(0);
String line = raFile.readLine();
//int firstTab = line.indexOf("\t");
//String keyParsed = line.substring(0,firstTab).trim();
String keyParsed = line.trim();
TreeMap tm = new TreeMap();
//int key = Integer.parseInt( keyParsed );
String key = (String)keyParsed;
long offset = 0;
//tm.put(new Integer(key), new Long(offset));
tm.put(key, new Long(offset));
while( line != null )
offset = raFile.getFilePointer();
line = raFile.readLine();
if(line == null)
break;
//firstTab = line.indexOf("\t");
//key = Integer.parseInt( line.substring(0,firstTab).trim() );
//key = (String)line.substring(0,firstTab).trim();//created
key = (String)line.trim();
tm.put(key, new Long(offset));
}//untill write in random access file
Object o = null;
long offsetMap = 0;
Iterator it = tm.keySet().iterator();
while(it.hasNext() )
o = it.next();
offsetMap = ((Long) tm.get(o)).longValue();
//index.writeInt(((String)o).intValue() );
index.writeUTF (((String)o) );
//index.writeUTF(offsetMap);
index.writeLong(offsetMap);
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
long endTime = System.currentTimeMillis();
System.out.println("\nTime to create index is "+(endTime-startTime)/1000+" seconds\n");
/*H2***********************************************************************************
* readAllOrdered() use index to output records in order
private void readAllOrdered()
if(index == null)
System.out.println("You need to create the index with option C");
return;
try{
index.seek(4);
long indexOffset = index.length();
int skipped = 4;
while(indexOffset > index.getFilePointer() && skipped ==4 )
long offset = index.readLong();
raFile.seek(offset);
System.out.println(raFile.readLine());
skipped = index.skipBytes(4);
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
/**H2**********************************************************************************
* findRecordIndex() use index to find record in order (binary search)
private void findRecordIndex(String value)
if(index == null)
System.out.println("You need to create the index with option C");
return;
long startTime = System.currentTimeMillis();
try{
long low = 0;
long length = index.length();
long last = (length/12) - 1;
long high = last;
long middle = high/2;
while(low <= high )
//get middle value
index.seek((middle)*12);
//index.seek(0);
//int midValue = index.readInt();
String midValue = (String)index.readUTF();
if(midValue.equals(value))
long raCursor = index.readLong();
raFile.seek(raCursor);
System.out.println(raFile.readLine() );
long endTime = System.currentTimeMillis();
System.out.println("\nTime to locate record with index is "+(endTime-startTime)+" milliseconds\n");
return;
if(!(midValue.equals(value)))
low = middle+1;
else
high = middle-1;
middle = (low+high)/2;
System.out.println("The key "+value+" is not in this file");
}catch(IOException io) {System.out.println("IOException in findRecordIndex: "+io); }
* readAll() reads each record in RandomAccessFile raFile and outputs each record to
* standard output (System.out.println)
private void readAll()
try{
raFile.seek(0);
String line = raFile.readLine();
while( line != null )
System.out.println(line);
line = raFile.readLine();
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
* findRecord() takes parameter key holding the key of the record to return
* returns the record as a String object
private String findRecord(String key )
long startTime = System.currentTimeMillis();
long offset = findStartOfRecord(key);
try{
if(offset >= 0)
raFile.seek(offset);
long endTime = System.currentTimeMillis();
System.out.println("Time to locate record is "+(endTime-startTime)+" milliseconds");
return raFile.readLine();
else
long endTime = System.currentTimeMillis();
System.out.println("Time to locate record is "+(endTime-startTime)+" milliseconds");
return "No record for key "+key;
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
return null;
* updateRecord(String key, int col, String value)
* parameters key - key value of record to update
* col - column of field to update
* value - new value for this field of the record
* method must find the record with key and update the field. The updated record must
* be put back in the file with all other records maintained.
private void updateRecord(String key, int col, String value)
try{
long cursor = findStartOfRecord(key);
if(cursor <0)
System.out.println("The record does not exist.");
else
raFile.seek(cursor);
String record = raFile.readLine();
long cursor2 = raFile.getFilePointer();
//Create byte array of all data after updated record
byte[] b = new byte[(int)raFile.length()-(int)cursor2];
raFile.readFully(b);
//Put cursor on record to update and write new record
raFile.seek(cursor);
String newLine = updateLine(record, col, value);
raFile.setLength(raFile.length()-(cursor2-cursor) ); //truncate old data
raFile.writeBytes(newLine.trim());
raFile.writeBytes("\n");
long offset = raFile.getFilePointer(); //start of data with new offsets
raFile.write(b);
if(index != null)
updateIndex(key, offset);
}catch(Exception e){System.out.println("File size failed in choice 4"); }
static private String updateLine(String line, int field, String newValue)
StringBuffer sb = new StringBuffer(line);
int index = -1;
for(int i=1;i<field;i++)
index = sb.indexOf("\t",index+1);
int index2 = sb.indexOf("\t",index+1);
if(index2<1)
index2 = sb.length()-1;
sb = sb.replace(index+1,index2,newValue);
return sb.toString();
* deleteRecord() takes parameter key holding the key of the record to delete
* the method must maintain validity of entire text file
* Locate a record, delete the record, rewrite the rest of file to remove empty
* space of deleted record
private void deleteRecord(String key)
try{
long cursor = findStartOfRecord(key);
//Create byte array to read in the rest of file
long cursor2 = raFile.getFilePointer();
byte[] b = new byte[(int)raFile.length()-(int)cursor2];
raFile.readFully(b);
raFile.seek(cursor);
raFile.write(b);
raFile.setLength(raFile.length()-(cursor2-cursor) ); //truncate old data
//update index file
if(index != null)
deleteIndexField(key);
updateIndex(key, cursor);
}catch(IOException io){System.out.println("IOException in deleteRecord: "+io); }
* updateIndex(String key, long cursorDataFile) - resets the offsets for all records in data file
* starting at cursorDataFile cursor location
private void updateIndex(String key, long cursorDataFile)
long startTime = System.currentTimeMillis();
try{
raFile.seek(cursorDataFile);
//build TreeMap of indices to update offsets.
String line = raFile.readLine();
if(line == null)
return;
int firstTab = line.indexOf("\t");
String keyParsed = line.substring(0,firstTab).trim();
TreeMap tm = new TreeMap();
int keyValue = Integer.parseInt( keyParsed );
long offset = cursorDataFile;
tm.put(new Integer(keyValue), new Long(offset));
while( line != null )
offset = raFile.getFilePointer();
line = raFile.readLine();
if(line ==null)
break;
firstTab = line.indexOf("\t");
keyValue = Integer.parseInt( line.substring(0,firstTab).trim() );
tm.put(new Integer(keyValue), new Long(offset));
Object o = null;
long offsetValue = 0;
Iterator it = tm.keySet().iterator();
keyValue =0;
int indexKey = 0;
index.seek(0);
while(it.hasNext() )
o = it.next();//get first ordered key from TreeMap to update in index
keyValue = ((Integer)o).intValue();
//obtain new offset for this key
offsetValue = ((Long) tm.get(o)).longValue();
//scan index to find next key to update offset
indexKey = index.readInt( );
while(indexKey < keyValue)
{ //get next indexKey value
index.skipBytes(8);
indexKey = index.readInt();
//past while when indexKey == key
index.writeLong(offsetValue);
//get next ordered index value to update
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
long endTime = System.currentTimeMillis();
System.out.println("\nTime to update index is "+(endTime-startTime)+" milliseconds\n");
* deleteIndexField(String key) - removes the 12 bytes for the index from the file index
private void deleteIndexField(String key)
int keyValue = Integer.parseInt(key.trim());
try{
long low = 0;
long length = index.length();
long last = (length/12) - 1;
long high = last;
long middle = high/2;
while(low <= high )
//get middle value
index.seek((middle)*12);
int midValue = index.readInt();
if(midValue == keyValue)
long cursorIndexDelete = index.getFilePointer() - 4;
long cursor = cursorIndexDelete+12; //index to delete
index.seek(cursor);
//read tail of index file
byte[] b = new byte[(int)index.length()-(int)cursor];
index.seek(cursor);
index.readFully(b);
//fill in index in order
index.seek(cursorIndexDelete);
//write back out rest of index file
index.write(b);
index.setLength(index.length() -12 );
return;
if(midValue < keyValue)
low = middle+1;
else
high = middle-1;
middle = (low+high)/2;
System.out.println("The key "+keyValue+" is not in this file");
}catch(IOException io) {System.out.println("IOException in findRecordIndex: "+io); }
* findStartOfRecord(String key) takes parameter key holding the key of the record to find
* returns the cursor position of located record
* Helper method to locate a record and find location of cursor
private long findStartOfRecord(String key)
long cursor = 0;
String keyValue = (String)key.trim();
try{
raFile.seek(0);
cursor = raFile.getFilePointer();
String line = raFile.readLine();
StringTokenizer st = null;
while( line != null )
st = new StringTokenizer(line);
//get first token (the key)
String keyLineValue = (String)st.nextToken().trim() ;
//System.out.println("Key: "+key+" "+line);
if (keyValue.equals( keyLineValue ))
return cursor;
cursor = raFile.getFilePointer();
line = raFile.readLine();
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
return -1;
* insertRecord() prompts for record to insert
* the method must maintain validity of entire text file
private void insertRecord(String record)
try{
raFile.seek(raFile.length());
long offset = raFile.length();
raFile.writeBytes(record.trim());
raFile.writeBytes("\n");
StringTokenizer st = new StringTokenizer(record);
//get first token (the key)
int recordKey = Integer.parseInt(st.nextToken().trim() );
if(index != null)
insertIndex(recordKey, offset);
}catch(IOException io){System.out.println("IOException insertRecord: "+io); }
* insertIndex(int key, long offset)
* adds to the index a new record
private void insertIndex(int key, long offset)
long startTime = System.currentTimeMillis();
//find location in index
try
index.seek(0);
long indexLength = index.length();
int skipped = 8;
while(indexLength > index.getFilePointer() && skipped ==8 )
long cursor = index.getFilePointer();
int next = index.readInt();
//insert key here
if(key < next)
{ //read rest of file
//long cursor2 = index.getFilePointer();
byte[] b = new byte[(int)index.length()-(int)cursor];
index.seek(cursor);
index.readFully(b);
//fill in index in order
index.seek(cursor);
index.writeInt(key);
index.writeLong(offset);
//write back out rest of index file
index.write(b);
long endTime = System.currentTimeMillis();
System.out.println("\nTime to update index is "+(endTime-startTime)+" milliseconds\n");
return;
skipped = index.skipBytes(8);
if(indexLength == index.getFilePointer() ) //add to end
index.writeInt(key);
index.writeLong(offset);
else
System.out.println("index did not insert: "+key);
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
* The below methods read in a line of input from standard input and create a
* RandomAccessFile to manipulate. printMenu() prints the menu to enter options
* The code works and should not need to be updated
//Input method to read a line from standard input
private String getLine()
{ String inputLine = "";
try{
inputLine = reader.readLine();
}catch(IOException e){
System.out.println(e);
System.exit(1);
}//end catch
return inputLine;
//Creates a RandomAccessFile object from text file
private void fileCreate()
// Specify the File to Manipulate
System.out.print("Enter the file name to manipulate:");
String fileName = getLine();
//Create a RandomAccessFile with read and write priveledges
try{
raFile = new RandomAccessFile(fileName, "rw" );
if(raFile.length() <1)
System.out.println("File has "+raFile.length()+" bytes. Is the file name correct?" );
catch(FileNotFoundException fnf){System.out.println("File not found in this directory"); }
catch(IOException io) {System.out.println("IOException"); }
private void printMenu()
{ System.out.println("\n\nSelect one of these options: ");
System.out.println(" 1 - Read and Output All Lines");
System.out.println(" 2 - Return Record with Key");
System.out.println(" 3 - Insert a New Record");
System.out.println(" 4 - Delete Record with Key");
System.out.println(" 5 - Update Record with Key");
System.out.println(" 6 - Output all lines ordered by key");
System.out.println(" 7 - Return Record with key using index");
System.out.println(" C - Create Index on Key");
System.out.println(" F - Specify Different Data File");
System.out.println(" X - Exit application");
System.out.print("Your choice: ");
}with regards
sure..)-Now Exception is ok. it dosen't match the Key
value. please execute once then you will know all
problems. I think i am doing mistake at line no 125
and 214 methods implementation. Please correct me
sir.The exception does not disappear unless there was a change to the code? Did you change the code you posted?
What is the mistake you think you are doing?
Which lines are 125 and 214? -
My Program throws EOFException..
Hi developers,
My program is algoritham project. It throws EOFException.Can you explain any body where i am doing error.
this is my code
import java.util.TreeMap;
import java.io.*;
import java.util.Iterator;
import java.util.StringTokenizer;
public class TableIndexSolution
private BufferedReader reader;
private RandomAccessFile raFile; //file to manipulated
private RandomAccessFile index;
public static void main(String[] args)
TableIndexSolution app = new TableIndexSolution();
app.init();
app.run();
private void init()
{ raFile = null;
reader = new BufferedReader(new InputStreamReader(System.in));
private void run()
{ // Continually read command from user in a loop and then do the requested query
String choice, sqlSt;
fileCreate();
printMenu();
choice = getLine();
while (!(choice.equals("X") || choice.equals("x")))
if (choice.equals("1"))
{// Read in and output entire raFile using API for class RandomAccessFile
readAll();
else if (choice.equals("2"))
{//Locate and output the record with the following key
System.out.print("Please enter the key to locate the record: ");
String key = getLine().trim(); //implemented below to read an integer from std.in
System.out.println(findRecord(key) );
else if (choice.equals("3"))
{// Prompt for a record to insert, then append to raFile
System.out.print("Enter the record:");
String record = getLine().trim();
insertRecord(record);
else if (choice.equals("4"))
{// prompt for key of record to delete
System.out.print("Please enter the key to locate the record to delete: ");
String key = getLine().trim();
deleteRecord( key);
else if (choice.equals("5"))
{//read in key value and call update method
System.out.print("Enter key of record to update: " );
String key = getLine();
System.out.print("Enter column number of field to update: ");
String column = getLine();
int col = Integer.parseInt(column);
System.out.print("Enter value of field to update: ");
String value = getLine();
updateRecord(key, col, value);
else if (choice.equals("6"))
readAllOrdered();
else if (choice.equals("7"))
System.out.print("Please enter the key to locate the record to find: ");
String key = getLine().trim();
//int keyValue = Integer.parseInt(key);
String keyValue = (String)key;
findRecordIndex(keyValue);
else if (choice.equals("C"))
createIndex();
else if (choice.equals("F"))
fileCreate();
else
System.out.println("Invalid input!");
printMenu();
choice = getLine();
try{
raFile.close();
if(index != null)
index.close();
reader.close();
catch(IOException io)
{System.out.println(io); }
/*H2*****************************************************************************
* createIndex() - creates a RandomAccessFile index to hold as bytes an integer index value
and an integer for the byte offset
private void createIndex()
long startTime = System.currentTimeMillis();
//create index file
try
index = new RandomAccessFile("index.dat", "rw" );
catch(FileNotFoundException fnf){System.out.println("File not found in this directory"); }
try
index.setLength(0); //create new index
index.seek(0);
raFile.seek(0);
String line = raFile.readLine();
//int firstTab = line.indexOf("\t");
//String keyParsed = line.substring(0,firstTab).trim();
String keyParsed = line.trim();
TreeMap tm = new TreeMap();
//int key = Integer.parseInt( keyParsed );
String key = (String)keyParsed;
long offset = 0;
//tm.put(new Integer(key), new Long(offset));
tm.put(key, new Long(offset));
while( line != null )
offset = raFile.getFilePointer();
line = raFile.readLine();
if(line == null)
break;
//firstTab = line.indexOf("\t");
//key = Integer.parseInt( line.substring(0,firstTab).trim() );
//key = (String)line.substring(0,firstTab).trim();//created
key = (String)line.trim();
tm.put(key, new Long(offset));
}//untill write in random access file
Object o = null;
long offsetMap = 0;
Iterator it = tm.keySet().iterator();
while(it.hasNext() )
o = it.next();
offsetMap = ((Long) tm.get(o)).longValue();
//index.writeInt(((String)o).intValue() );
index.writeUTF (((String)o) );
//index.writeUTF(offsetMap);
index.writeLong(offsetMap);
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
long endTime = System.currentTimeMillis();
System.out.println("\nTime to create index is "+(endTime-startTime)/1000+" seconds\n");
/*H2***********************************************************************************
* readAllOrdered() use index to output records in order
private void readAllOrdered()
if(index == null)
System.out.println("You need to create the index with option C");
return;
try{
index.seek(4);
long indexOffset = index.length();
int skipped = 4;
while(indexOffset > index.getFilePointer() && skipped ==4 )
long offset = index.readLong();
raFile.seek(offset);
System.out.println(raFile.readLine());
skipped = index.skipBytes(4);
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
/**H2**********************************************************************************
* findRecordIndex() use index to find record in order (binary search)
private void findRecordIndex(String value)
if(index == null)
System.out.println("You need to create the index with option C");
return;
long startTime = System.currentTimeMillis();
try{
long low = 0;
long length = index.length();
long last = (length/12) - 1;
long high = last;
long middle = high/2;
while(low <= high )
//get middle value
index.seek((middle)*12);
//index.seek(0);
//int midValue = index.readInt();
String midValue = (String)index.readUTF();
if(midValue.equals(value))
long raCursor = index.readLong();
raFile.seek(raCursor);
System.out.println(raFile.readLine() );
long endTime = System.currentTimeMillis();
System.out.println("\nTime to locate record with index is "+(endTime-startTime)+" milliseconds\n");
return;
if(!(midValue.equals(value)))
low = middle+1;
else
high = middle-1;
middle = (low+high)/2;
System.out.println("The key "+value+" is not in this file");
}catch(IOException io) {System.out.println("IOException in findRecordIndex: "+io); }
* readAll() reads each record in RandomAccessFile raFile and outputs each record to
* standard output (System.out.println)
private void readAll()
try{
raFile.seek(0);
String line = raFile.readLine();
while( line != null )
System.out.println(line);
line = raFile.readLine();
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
* findRecord() takes parameter key holding the key of the record to return
* returns the record as a String object
private String findRecord(String key )
long startTime = System.currentTimeMillis();
long offset = findStartOfRecord(key);
try{
if(offset >= 0)
raFile.seek(offset);
long endTime = System.currentTimeMillis();
System.out.println("Time to locate record is "+(endTime-startTime)+" milliseconds");
return raFile.readLine();
else
long endTime = System.currentTimeMillis();
System.out.println("Time to locate record is "+(endTime-startTime)+" milliseconds");
return "No record for key "+key;
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
return null;
* updateRecord(String key, int col, String value)
* parameters key - key value of record to update
* col - column of field to update
* value - new value for this field of the record
* method must find the record with key and update the field. The updated record must
* be put back in the file with all other records maintained.
private void updateRecord(String key, int col, String value)
try{
long cursor = findStartOfRecord(key);
if(cursor <0)
System.out.println("The record does not exist.");
else
raFile.seek(cursor);
String record = raFile.readLine();
long cursor2 = raFile.getFilePointer();
//Create byte array of all data after updated record
byte[] b = new byte[(int)raFile.length()-(int)cursor2];
raFile.readFully(b);
//Put cursor on record to update and write new record
raFile.seek(cursor);
String newLine = updateLine(record, col, value);
raFile.setLength(raFile.length()-(cursor2-cursor) ); //truncate old data
raFile.writeBytes(newLine.trim());
raFile.writeBytes("\n");
long offset = raFile.getFilePointer(); //start of data with new offsets
raFile.write(b);
if(index != null)
updateIndex(key, offset);
}catch(Exception e){System.out.println("File size failed in choice 4"); }
static private String updateLine(String line, int field, String newValue)
StringBuffer sb = new StringBuffer(line);
int index = -1;
for(int i=1;i<field;i++)
index = sb.indexOf("\t",index+1);
int index2 = sb.indexOf("\t",index+1);
if(index2<1)
index2 = sb.length()-1;
sb = sb.replace(index+1,index2,newValue);
return sb.toString();
* deleteRecord() takes parameter key holding the key of the record to delete
* the method must maintain validity of entire text file
* Locate a record, delete the record, rewrite the rest of file to remove empty
* space of deleted record
private void deleteRecord(String key)
try{
long cursor = findStartOfRecord(key);
//Create byte array to read in the rest of file
long cursor2 = raFile.getFilePointer();
byte[] b = new byte[(int)raFile.length()-(int)cursor2];
raFile.readFully(b);
raFile.seek(cursor);
raFile.write(b);
raFile.setLength(raFile.length()-(cursor2-cursor) ); //truncate old data
//update index file
if(index != null)
deleteIndexField(key);
updateIndex(key, cursor);
}catch(IOException io){System.out.println("IOException in deleteRecord: "+io); }
* updateIndex(String key, long cursorDataFile) - resets the offsets for all records in data file
* starting at cursorDataFile cursor location
private void updateIndex(String key, long cursorDataFile)
long startTime = System.currentTimeMillis();
try{
raFile.seek(cursorDataFile);
//build TreeMap of indices to update offsets.
String line = raFile.readLine();
if(line == null)
return;
int firstTab = line.indexOf("\t");
String keyParsed = line.substring(0,firstTab).trim();
TreeMap tm = new TreeMap();
int keyValue = Integer.parseInt( keyParsed );
long offset = cursorDataFile;
tm.put(new Integer(keyValue), new Long(offset));
while( line != null )
offset = raFile.getFilePointer();
line = raFile.readLine();
if(line ==null)
break;
firstTab = line.indexOf("\t");
keyValue = Integer.parseInt( line.substring(0,firstTab).trim() );
tm.put(new Integer(keyValue), new Long(offset));
Object o = null;
long offsetValue = 0;
Iterator it = tm.keySet().iterator();
keyValue =0;
int indexKey = 0;
index.seek(0);
while(it.hasNext() )
o = it.next();//get first ordered key from TreeMap to update in index
keyValue = ((Integer)o).intValue();
//obtain new offset for this key
offsetValue = ((Long) tm.get(o)).longValue();
//scan index to find next key to update offset
indexKey = index.readInt( );
while(indexKey < keyValue)
{ //get next indexKey value
index.skipBytes(8);
indexKey = index.readInt();
//past while when indexKey == key
index.writeLong(offsetValue);
//get next ordered index value to update
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
long endTime = System.currentTimeMillis();
System.out.println("\nTime to update index is "+(endTime-startTime)+" milliseconds\n");
* deleteIndexField(String key) - removes the 12 bytes for the index from the file index
private void deleteIndexField(String key)
int keyValue = Integer.parseInt(key.trim());
try{
long low = 0;
long length = index.length();
long last = (length/12) - 1;
long high = last;
long middle = high/2;
while(low <= high )
//get middle value
index.seek((middle)*12);
int midValue = index.readInt();
if(midValue == keyValue)
long cursorIndexDelete = index.getFilePointer() - 4;
long cursor = cursorIndexDelete+12; //index to delete
index.seek(cursor);
//read tail of index file
byte[] b = new byte[(int)index.length()-(int)cursor];
index.seek(cursor);
index.readFully(b);
//fill in index in order
index.seek(cursorIndexDelete);
//write back out rest of index file
index.write(b);
index.setLength(index.length() -12 );
return;
if(midValue < keyValue)
low = middle+1;
else
high = middle-1;
middle = (low+high)/2;
System.out.println("The key "+keyValue+" is not in this file");
}catch(IOException io) {System.out.println("IOException in findRecordIndex: "+io); }
* findStartOfRecord(String key) takes parameter key holding the key of the record to find
* returns the cursor position of located record
* Helper method to locate a record and find location of cursor
private long findStartOfRecord(String key)
long cursor = 0;
String keyValue = (String)key.trim();
try{
raFile.seek(0);
cursor = raFile.getFilePointer();
String line = raFile.readLine();
StringTokenizer st = null;
while( line != null )
st = new StringTokenizer(line);
//get first token (the key)
String keyLineValue = (String)st.nextToken().trim() ;
//System.out.println("Key: "+key+" "+line);
if (keyValue.equals( keyLineValue ))
return cursor;
cursor = raFile.getFilePointer();
line = raFile.readLine();
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
return -1;
* insertRecord() prompts for record to insert
* the method must maintain validity of entire text file
private void insertRecord(String record)
try{
raFile.seek(raFile.length());
long offset = raFile.length();
raFile.writeBytes(record.trim());
raFile.writeBytes("\n");
StringTokenizer st = new StringTokenizer(record);
//get first token (the key)
int recordKey = Integer.parseInt(st.nextToken().trim() );
if(index != null)
insertIndex(recordKey, offset);
}catch(IOException io){System.out.println("IOException insertRecord: "+io); }
* insertIndex(int key, long offset)
* adds to the index a new record
private void insertIndex(int key, long offset)
long startTime = System.currentTimeMillis();
//find location in index
try
index.seek(0);
long indexLength = index.length();
int skipped = 8;
while(indexLength > index.getFilePointer() && skipped ==8 )
long cursor = index.getFilePointer();
int next = index.readInt();
//insert key here
if(key < next)
{ //read rest of file
//long cursor2 = index.getFilePointer();
byte[] b = new byte[(int)index.length()-(int)cursor];
index.seek(cursor);
index.readFully(b);
//fill in index in order
index.seek(cursor);
index.writeInt(key);
index.writeLong(offset);
//write back out rest of index file
index.write(b);
long endTime = System.currentTimeMillis();
System.out.println("\nTime to update index is "+(endTime-startTime)+" milliseconds\n");
return;
skipped = index.skipBytes(8);
if(indexLength == index.getFilePointer() ) //add to end
index.writeInt(key);
index.writeLong(offset);
else
System.out.println("index did not insert: "+key);
}catch(IOException io) {System.out.println("IOException in readAll: "+io); }
* The below methods read in a line of input from standard input and create a
* RandomAccessFile to manipulate. printMenu() prints the menu to enter options
* The code works and should not need to be updated
//Input method to read a line from standard input
private String getLine()
{ String inputLine = "";
try{
inputLine = reader.readLine();
}catch(IOException e){
System.out.println(e);
System.exit(1);
}//end catch
return inputLine;
//Creates a RandomAccessFile object from text file
private void fileCreate()
// Specify the File to Manipulate
System.out.print("Enter the file name to manipulate:");
String fileName = getLine();
//Create a RandomAccessFile with read and write priveledges
try{
raFile = new RandomAccessFile(fileName, "rw" );
if(raFile.length() <1)
System.out.println("File has "+raFile.length()+" bytes. Is the file name correct?" );
catch(FileNotFoundException fnf){System.out.println("File not found in this directory"); }
catch(IOException io) {System.out.println("IOException"); }
private void printMenu()
{ System.out.println("\n\nSelect one of these options: ");
System.out.println(" 1 - Read and Output All Lines");
System.out.println(" 2 - Return Record with Key");
System.out.println(" 3 - Insert a New Record");
System.out.println(" 4 - Delete Record with Key");
System.out.println(" 5 - Update Record with Key");
System.out.println(" 6 - Output all lines ordered by key");
System.out.println(" 7 - Return Record with key using index");
System.out.println(" C - Create Index on Key");
System.out.println(" F - Specify Different Data File");
System.out.println(" X - Exit application");
System.out.print("Your choice: ");
}this is data1.txt file
FVQYG LEMQJI RTVHW LTPEJ
wtfwfvoyfv ppjguuezx vgiug wxguku
neuexkmhwy xllift pcjdo tnukil
nuojgltqav xsiajz kbwtqht otkkleii
zsudggdibm jsnbrszi uhsdnowzl rumur
yzjkghmqaq ttyzf wbdmayzrm gbwvbj
jbfdgkeesb ujopbiged jgvjh hqsviyfhm
cwaqvfesay faygvckgp xqadb oxpcswbvs
pqgedbeesg yrnzwbt pmgxpwbwo brgqysjjy
xrgbxoqnkf fpfyh hnrzg twebyugf
ncqytrwbrd hjzticyyp dxwvl xfnavww
thanking you
with regards
sure..)-Now Exception is ok. it dosen't match the Key
value. please execute once then you will know all
problems. I think i am doing mistake at line no 125
and 214 methods implementation. Please correct me
sir.The exception does not disappear unless there was a change to the code? Did you change the code you posted?
What is the mistake you think you are doing?
Which lines are 125 and 214? -
How to implement logger in this ftp server
I have written a FTP Server that is used by the clients to upload xml over to the server.
Currently it is using a console and it is printing stuff out on a console.
I have tried a lot to implement a logger class so that all console messages get written to a file.
But it has not been working out at all.
I would deeply appreciate if all you java gurus out there could modify the code given below to correctly log messages to a log file.
Please do Explain if possible ...I will try to rectify this issue in several other applications i developed as well.
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.Format;
import java.lang.Object;
import java.lang.*;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
public class FTPServer
{ public static void main(String args[]) throws Exception
{ ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
class transferfile extends Thread
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
transferfile(Socket soc)
{ try
{ ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
System.out.println("External IP of Client ..." + ClientSoc.getInetAddress());
//System.out.println("FTP Client Connected ..." + ClientSoc.getRemoteSocketAddress());
start();
catch(Exception ex)
//encrypto routine starts
class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
// 8-byte Salt
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03 };
// Iteration count
int iterationCount = 19;
DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
//added later on
in.close();
out.close();
} catch (java.io.IOException e) {
} //encryptor routine ends
//not implemented right now as we arent using the ftp server to download stuff...can be activated later on if we want
void SendFile() throws Exception
String filename=din.readUTF();
File f=new File(filename);
if(!f.exists())
dout.writeUTF("File Not Found");
return;
else
{ dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
while(ch!=-1);
fin.close();
dout.writeUTF("File Received Successfully");
String Compare(String filename) throws Exception
///dout.writeUTF("entering compare");
String dateTempString=new String();
Date dateValue=new Date();
SimpleDateFormat formatter = new SimpleDateFormat ("hhmmss");
dateTempString = formatter.format(dateValue);
File dir1 = new File("C:\\FTPnew");
boolean success2 = dir1.mkdir();
if (!success2) {
// Directory creation failed /Already Exists
File dir = new File("C:\\FTPnew\\server");
boolean success = dir.mkdir();
if (!success) {
// Directory creation failed /Already Exists
File ftemp=new File(dir,dateTempString + filename);
File fnewtemp=new File(dir,"new-enc-"+filename);
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
FileOutputStream fout=new FileOutputStream(fnewtemp);
int ch;
String temp;
do
{ temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
//dout.writeUTF("written temp en file");
// Decrypt
encrypter.decrypt(new FileInputStream(fnewtemp),
new FileOutputStream(ftemp));
//String Option;
dout.writeUTF("Delete");
System.out.println("File Upload Successfull--Duplicate file with timestamp Created");
boolean success1 = fnewtemp.delete();
return "hello" ;
void ReceiveFile() throws Exception
String ip=din.readUTF();
System.out.println("\tRequest Coming from Internal IP Address : "+ ip);
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
return;
// Destination directory
File dir11 = new File("C:\\FTPnew");
boolean success22 = dir11.mkdir();
if (!success22) {
// Directory creation failed /Already Exists
File dir = new File("C:\\FTPnew\\server");
boolean success21 = dir.mkdir();
if (!success21) {
// Directory creation failed /Already Exists
File f=new File(dir ,"enc-"+filename);
File fe=new File(dir,filename);
String option;
if(fe.exists())
//dout.writeUTF("File Already Exists");
String compvalue = Compare(filename);
//dout.writeUTF(compvalue);
if(compvalue.compareTo("hello")==0)
//dout.writeUTF("Transfer Completed");
return;
option=din.readUTF();
else
//dout.writeUTF("SendFile");
option="Y";
if(option.compareTo("Y")==0)
// Generate a temporary key.
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{ temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
// Decrypt
encrypter.decrypt(new FileInputStream(f),
new FileOutputStream(fe));
boolean success2 = f.delete();
dout.writeUTF("Delete");
System.out.println("File Upload Successfull");
else
return;
public void run()
while(true)
try
String Command=din.readUTF();
if(Command.compareTo("SEND")==0)
System.out.println("\tSEND Command Received ...");
ReceiveFile();
continue;
catch(Exception ex)
//System.out.println("\tClient Terminated Abnormally ...........");
continue;
}Stick a
Logger log = Logger.getLogger( "me ftp server" );at the top.
Checn Sys.out.println to log.info( ... )
Add a logging prefs file.
http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/overview.html -
Issue with Ftp Client / Server using Sockets
I have developed a Ftp Client and a Ftp Server. The client Connects to the Ftp Server and sends files to the ftp server. It is a multi threaded server and can have multiple clients connecting to it.
If a client goes down...the server waits till the client comes up
Similarly the client waits if a server goes down and reconnects when the server is again up and running
i am having a strange issue here. When two clients go down and reconnect to the server...They take a long time to connect and transferring of files takes a long time...
Other wise in all other scenarios the duo work properly.
Any feedback and suggestion about this strange issue from all you java gurus out there will be deeply appreciated.
Here is the client code
import java.net.*;
import java.net.Socket;
import java.net.InetAddress;
import java.io.*;
import java.io.File;
import java.util.*;
import java.lang.*;
import java.lang.Object;
import javax.crypto.*;
import java.util.regex.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.File.*;
import java.nio.channels.FileLock;
public class FTPClient {
public static void main(String[] args) throws Exception
Timer timer = new Timer("Test Timer");
timer.scheduleAtFixedRate(new TimerTask()
private int counter = 0;
public void run() {
try {
System.out.println(counter++);
Socket soc=new Socket("xxx.x.x.xx",5217);
System.out.println("Socket Initialised.");
transferfileClient t=new transferfileClient(soc);
t.SendFile();
System.out.println("run complete.");
catch(Exception ex)
}, 10000, 40000);
static class transferfileClient
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
BufferedReader br;
transferfileClient(Socket soc)
try
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
catch(Exception ex)
//encrypto routine starts
class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
// 8-byte Salt
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
// Iteration count
int iterationCount = 19;
DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
} //encryptor routine ends
void SendFile() throws Exception
try
String directoryName;
// File object referring to the directory.
String[] files; // Array of file names in the directory.
//directory = new File ( "C:\\FTP\\" ) ;
File directory1 = new File("C:\\FTP");
boolean successmk = directory1.mkdir();
if (!successmk) {
// Directory creation failed /Already Exists
File directory = new File("C:\\FTP\\ftpc");
boolean successmk1 = directory.mkdir();
if (!successmk1) {
// Directory creation failed /Already Exists
//directory = new File ( "E:\\FTP-encrypted" ) ;
if (directory.isDirectory() == false) {
if (directory.exists() == false)
System.out.println("There is no such directory!");
else
System.out.println("That file is not a directory.");
else {
files = directory.list();
System.out.println("Files in directory \"" + directory + "\":");
for (int i = 0; i < files.length; i++)
String patternStr = "xml";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(files);
boolean matchFound = matcher.find();
if (matchFound) {
System.out.println(" " + files[i]);
String filename;
filename=files[i];
File f=new File(directory,filename);
FileLock lock = null;
FileOutputStream fos = new FileOutputStream(f, true);
lock = fos.getChannel().tryLock();
if (lock == null) {
System.out.println(" Failed to get the file lock: means that the file is locked by other instance.");
fos.close();
else
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
//byte[] ipAddr = addr.getAddress();
String ip= addr.toString();
// Get hostname
//String hostname = addr.getHostName();
System.out.println(" Lock Acquired.");
lock.release();
fos.close();
dout.writeUTF("SEND");
dout.writeUTF(ip);
dout.writeUTF(filename);
//String msgFromServer=din.readUTF();
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
// Encrypt
FileInputStream fino=new FileInputStream(f);
encrypter.encrypt(fino,
new FileOutputStream("ciphertext.txt"));
fino.close();
FileInputStream fin=new FileInputStream("ciphertext.txt");
int ch;
do
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
while(ch!=-1);
fin.close();
String option;
option=din.readUTF();
if((option.compareTo("Delete")==0))
boolean success = (new File("ciphertext.txt")).delete();
boolean success1 = f.delete();
if (success) {
System.out.println("File Sent ...");
if (success1) {
System.out.println("--File deleted from Client ...");
for (int j = 0; j < 999999999; j++){}
}//pattermatch loop ends here
else
{ //System.out.println(" " + "Not an XML file-------->" +files[i]);
for (int jb = 0; jb < 111999999; jb++){}
}// for loop ends here for files in directory
}//else loop ends for directory files listing
System.out.println("sendfile finished...");
return;
} catch(Exception ex) {ex.printStackTrace();}
}//sendfile ends here
public void displayMenu() throws Exception
System.out.println(" Send File");
SendFile();
return;
And here is the server code...
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.Format;
import java.lang.Object;
import java.lang.*;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
public class FTPServer
{ public static void main(String args[]) throws Exception
{ ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
class transferfile extends Thread
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
transferfile(Socket soc)
{ try
{ ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
System.out.println("External IP of Client ..." + ClientSoc.getInetAddress());
//System.out.println("FTP Client Connected ..." + ClientSoc.getRemoteSocketAddress());
start();
catch(Exception ex)
//encrypto routine starts
class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
// 8-byte Salt
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03 };
// Iteration count
int iterationCount = 19;
DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
//added later on
in.close();
out.close();
} catch (java.io.IOException e) {
} //encryptor routine ends
//not implemented right now as we arent using the ftp server to download stuff...can be activated later on if we want
void SendFile() throws Exception
String filename=din.readUTF();
File f=new File(filename);
if(!f.exists())
dout.writeUTF("File Not Found");
return;
else
{ dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
while(ch!=-1);
fin.close();
dout.writeUTF("File Received Successfully");
String Compare(String filename) throws Exception
///dout.writeUTF("entering compare");
String dateTempString=new String();
Date dateValue=new Date();
SimpleDateFormat formatter = new SimpleDateFormat ("hhmmss");
dateTempString = formatter.format(dateValue);
File dir1 = new File("C:\\FTPnew");
boolean success2 = dir1.mkdir();
if (!success2) {
// Directory creation failed /Already Exists
File dir = new File("C:\\FTPnew\\server");
boolean success = dir.mkdir();
if (!success) {
// Directory creation failed /Already Exists
File ftemp=new File(dir,dateTempString + filename);
File fnewtemp=new File(dir,"new-enc-"+filename);
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
FileOutputStream fout=new FileOutputStream(fnewtemp);
int ch;
String temp;
do
{ temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
//dout.writeUTF("written temp en file");
// Decrypt
encrypter.decrypt(new FileInputStream(fnewtemp),
new FileOutputStream(ftemp));
//String Option;
dout.writeUTF("Delete");
System.out.println("File Upload Successfull--Duplicate file with timestamp Created");
boolean success1 = fnewtemp.delete();
return "hello" ;
void ReceiveFile() throws Exception
String ip=din.readUTF();
System.out.println("\tRequest Coming from Internal IP Address : "+ ip);
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
return;
// Destination directory
File dir11 = new File("C:\\FTPnew");
boolean success22 = dir11.mkdir();
if (!success22) {
// Directory creation failed /Already Exists
File dir = new File("C:\\FTPnew\\server");
boolean success21 = dir.mkdir();
if (!success21) {
// Directory creation failed /Already Exists
File f=new File(dir ,"enc-"+filename);
File fe=new File(dir,filename);
String option;
if(fe.exists())
//dout.writeUTF("File Already Exists");
String compvalue = Compare(filename);
//dout.writeUTF(compvalue);
if(compvalue.compareTo("hello")==0)
//dout.writeUTF("Transfer Completed");
return;
option=din.readUTF();
else
//dout.writeUTF("SendFile");
option="Y";
if(option.compareTo("Y")==0)
// Generate a temporary key.
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{ temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
// Decrypt
encrypter.decrypt(new FileInputStream(f),
new FileOutputStream(fe));
boolean success2 = f.delete();
dout.writeUTF("Delete");
System.out.println("File Upload Successfull");
else
return;
public void run()
while(true)
try
String Command=din.readUTF();
if(Command.compareTo("SEND")==0)
System.out.println("\tSEND Command Received ...");
ReceiveFile();
continue;
catch(Exception ex)
//System.out.println("\tClient Terminated Abnormally ...........");
continue;Please note that this is not an FTP client and server. FTP is defined by a standard IETF protocol and this isn't it.
Then, move the following lines:
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
System.out.println("External IP of Client ..." + ClientSoc.getInetAddress());
//System.out.println("FTP Client Connected ..."+ClientSoc.getRemoteSocketAddress());from the constructor into the run() method. i.e. don't do anything with the socket in the thread which handles the accept(). -
Parsing XML from a socket that does not close
Hi -
I've seen similar questions to this already posted, but either they did not really apply to my situation or they were not answered.
I have to read messages from a server and process them individually, but the protocol does not indicate the message length or give any sort of terminating character. You only know you have a complete message because it will be a well formed XML fragment. To complicate matters more, there could be extra binary data preceding each XML message. I must stress that I did not write this server, and I have no influence over the protocol at all, so while I certainly agree that this is not such a good protocol, changing it is not an option.
I'm hoping that there is a reasonable way to deal with this with an existing parser. Ironically, I don't really need to parse the XML at all, I just need to know when the current message is over but the only indication I get is that it will be the end of an XML fragment.
I do have the ability to strip off the non-XML binary data, so if there is some way that I can give the stream to a SAX (or other) parser when I know XML is coming and have it inform me when tags begin and end, or ideally inform me when it is done a complete XML fragment, that would be perfect. I'm aware of how to do this using SAX normally, but it seems that it will not function correctly when there is no EOF or other indication that the document has ended.
The best algorithm I have come up with (and it's pretty cheesy) is:
1. Start with a string buffer.
2. Append data from the socket to the buffer one byte at a time.
3. Keep checking if there is a '<' character that is not followed by '?' or '!'. (ie - don't concern myself with the special XML elements that don't close with '/>' or </tagName>. I keep them in the buffer to pass on when I'm done though.)
4. When I get my first tag with <tagName> I make note of what this tag is and increment a counter. If the tag is self closing, then I'm done.
5. Anytime I see this tag I increment the counter.
6. Anytime I see </tagName> I decrement the counter. If the counter = 0, I am done.
7. I pass on the entire message, preceding binary data, special XML tags and the fragment to the module that actually processes it.
This has a few problems. I'll have to go out of my way to support multiple character encodings, I'll have to be careful to catch all the special XML tags, and its quite CPU intensive to be interested in every single character that comes down the pipe (but I suppose this is not avoidable). Also, I just don't like to re-invent the wheel because I'm likely to make an error that a well established parser would not make.
Does anyone have any suggestions for this, or know of a parser that will deal with fragments using streams that don't close?
Thanks!The parser expects to read to the end of the stream. If you closed the stream right after you wrote to it, I bet it would work. You wouldn't want to close the stream though would you? Try sending the string using a DataOuputStream and calling DataOutputStream.writeUTF(String) on the client side. Then, on the server side call String str = in.readUTF() (where 'in' is a DataInputStream). Then wrap the string in a StringReader and give the StringReader to the parser as it's input source.
-
How to Implement simple Timer in this code
Hi there guys,
This is a small ftp client that i wrote. It has encryption and all bulit into it. I want to initiate the sendfile function every 5 minutes.
The program starts with the displaymenu function wherein a menu with various options is displayed.
How Do i Do that? I went online and tried doing it myself but cud not possibly think of a reason as to why my changes were not working.
Here is the basic code. I earnestly hope that some of you guys out there will help me. This is a very simple problem and sometimes it is the finer point that eludes us. any help will be deeply appreciated
import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;
import javax.crypto.*;
import java.util.regex.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
class FTPClient
public static void main(String args[]) throws Exception
Socket soc=new Socket("127.0.0.1",5217);
transferfileClient t=new transferfileClient(soc);
t.displayMenu();
class transferfileClient
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
BufferedReader br;
transferfileClient(Socket soc)
try
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
catch(Exception ex)
//encrypto routine starts
class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
// 8-byte Salt
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
// Iteration count
int iterationCount = 19;
DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
} //encryptor routine ends
void SendFile() throws Exception
String directoryName; // Directory name entered by the user.
File directory; // File object referring to the directory.
String[] files; // Array of file names in the directory.
//TextIO.put("Enter a directory name: ");
//directoryName = TextIO.getln().trim();
directory = new File ( "E:\\FTP-encrypted\\FTPClient" ) ;
if (directory.isDirectory() == false) {
if (directory.exists() == false)
System.out.println("There is no such directory!");
else
System.out.println("That file is not a directory.");
else {
files = directory.list();
System.out.println("Files in directory \"" + directory + "\":");
for (int i = 0; i < files.length; i++)
String patternStr = "xml";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(files);
boolean matchFound = matcher.find();
if (matchFound) {
dout.writeUTF("SEND");
System.out.println(" " + files[i]);
String filename;
filename=files[i];
File f=new File(filename);
dout.writeUTF(filename);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Already Exists")==0)
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="Y")
dout.writeUTF("Y");
else
dout.writeUTF("N");
return;
System.out.println("Sending File ...");
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
System.out.println("Secret key generated ...");
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
// Encrypt
FileInputStream fino=new FileInputStream(f);
System.out.println("Initialised ...");
encrypter.encrypt(fino,
new FileOutputStream("ciphertext.txt"));
System.out.println("generated ...");
fino.close();
FileInputStream fin=new FileInputStream("ciphertext.txt");
int ch;
do
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
while(ch!=-1);
fin.close();
boolean success = (new File("ciphertext.txt")).delete();
if (success) {
System.out.println("temp file deleted .../n/n");
for (int j = 0; j < 999999999; j++){}
}//pattermatch loop ends here
else
{ System.out.println(" " + "Not an XML file-------->" +files[i]); }
}// for loop ends here for files in directory
}//else loop ends for directory files listing
System.out.println(din.readUTF());
}//sendfile ends here
void ReceiveFile() throws Exception
String fileName;
System.out.print("Enter File Name :");
fileName=br.readLine();
dout.writeUTF(fileName);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Not Found")==0)
System.out.println("File not found on Server ...");
return;
else if(msgFromServer.compareTo("READY")==0)
System.out.println("Receiving File ...");
File f=new File(fileName);
if(f.exists())
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="N")
dout.flush();
return;
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
System.out.println(din.readUTF());
public void displayMenu() throws Exception
while(true)
System.out.println("[ MENU ]");
System.out.println("1. Send File");
System.out.println("2. Receive File");
System.out.println("3. Exit");
System.out.print("\nEnter Choice :");
int choice;
choice=Integer.parseInt(br.readLine());
if(choice==1)
SendFile();
else if(choice==2)
dout.writeUTF("GET");
ReceiveFile();
else
dout.writeUTF("DISCONNECT");
System.exit(1);here is a simple demo of a Timer usage.
public class Scheduler{
private Timer timer = null;
private FTPClient client = null;
public static void main(String args[]){
new Scheduler(5000);
public Scheduler(int seconds) {
client = new FTPClient();
timer = new Timer();
timer.schedule(new fileTransferTask(), seconds*1000);
timer.scheduleAtFixedRate(new FileTransferTask(client), seconds, seconds);
public class FileTransferTask extends TimerTask{
private FTPClient client = null;
public FileTransferTask(FTPClient client){
this.client = client;
public void run(){
client.sendFile();
public class FTPClient{
public void sendFile(){
// code to send the file by FTP
}the timer will will schedule the "task": scheduleAtFixRate( TimerTask, long delay, long interval)
It basically spawn a thread (this thread is the class that you
implements TimerTask..which in this example is the FileTransferTask)
The thread will then sleep until the time specified and once it wake..it
will execute the code in the the run() method. This is why you want to
pass a reference of any class that this TimerTask will use (that's why
we pass the FTPClient reference..so we can invoke the object's
sendFile method). -
Modify Record Number in a Random Access File
Hi Does anyone know if I can modify the record number in the random access file hardware.dat for each hardware record each time and update it in hardware.dat to display it? Also why does it say "Record does not exist" if I modify the record number for a hardware and try to update it but could not find that record?
Here is the code below:
// Exercise 14.11: HardwareRecord.java
package org.egan; // packaged for reuse
public class HardwareRecord
private int recordNumber;
private String toolName;
private int quantity;
private double cost;
// no-argument constructor calls other constructor with default values
public HardwareRecord()
this(0,"",0,0.0); // call four-argument constructor
} // end no-argument HardwareRecord constructor
// initialize a record
public HardwareRecord(int number, String tool, int amount, double price)
setRecordNumber(number);
setToolName(tool);
setQuantity(amount);
setCost(price);
} // end four-argument HardwareRecord constructor
// set record number
public void setRecordNumber(int number)
recordNumber = number;
} // end method setRecordNumber
// get record number
public int getRecordNumber()
return recordNumber;
} // end method getRecordNumber
// set tool name
public void setToolName(String tool)
toolName = tool;
} // end method setToolName
// get tool name
public String getToolName()
return toolName;
} // end method getToolName
// set quantity
public void setQuantity(int amount)
quantity = amount;
} // end method setQuantity
// get quantity
public int getQuantity()
return quantity;
} // end method getQuantity
// set cost
public void setCost(double price)
cost = price;
} // end method setCost
// get cost
public double getCost()
return cost;
} // end method getCost
} // end class HardwareRecord-------------------------------------------------------------------------------------------------
// Exercise 14.11: RandomAccessHardwareRecord.java
// Subclass of HardwareRecord for random-access file programs.
package org.egan; // package for reuse
import java.io.RandomAccessFile;
import java.io.IOException;
public class RandomAccessHardwareRecord extends HardwareRecord
public static final int SIZE = 46;
// no-argument constructor calls other constructor with default values
public RandomAccessHardwareRecord()
this(0,"",0,0.0);
} // end no-argument RandomAccessHardwareRecord constructor
// initialize a RandomAccessHardwareRecord
public RandomAccessHardwareRecord(int number, String tool, int amount, double price)
super(number,tool,amount,price);
} // end four-argument RandomAccessHardwareRecord constructor
// read a record from a specified RandomAccessFile
public void read(RandomAccessFile file) throws IOException
setRecordNumber(file.readInt());
setToolName(readName(file));
setQuantity(file.readInt());
setCost(file.readDouble());
} // end method read
// ensure that name is proper length
private String readName(RandomAccessFile file) throws IOException
char name[] = new char[15], temp;
for(int count = 0; count < name.length; count++)
temp = file.readChar();
name[count] = temp;
} // end for
return new String(name).replace('\0',' ');
} // end method readName
// write a record to specified RandomAccessFile
public void write(RandomAccessFile file) throws IOException
file.writeInt(getRecordNumber());
writeName(file, getToolName());
file.writeInt(getQuantity());
file.writeDouble(getCost());
} // end method write
// write a name to file; maximum of 15 characters
private void writeName(RandomAccessFile file, String name) throws IOException
StringBuffer buffer = null;
if (name != null)
buffer = new StringBuffer(name);
else
buffer = new StringBuffer(15);
buffer.setLength(15);
file.writeChars(buffer.toString());
} // end method writeName
} // end RandomAccessHardwareRecord-------------------------------------------------------------------------------------------------
// Exercise 14.11: CreateRandomFile.java
// creates random-access file by writing 100 empty records to disk.
import java.io.IOException;
import java.io.RandomAccessFile;
import org.egan.RandomAccessHardwareRecord;
public class CreateRandomFile
private static final int NUMBER_RECORDS = 100;
// enable user to select file to open
public void createFile()
RandomAccessFile file = null;
try // open file for reading and writing
file = new RandomAccessFile("hardware.dat","rw");
RandomAccessHardwareRecord blankRecord = new RandomAccessHardwareRecord();
// write 100 blank records
for (int count = 0; count < NUMBER_RECORDS; count++)
blankRecord.write(file);
// display message that file was created
System.out.println("Created file hardware.dat.");
System.exit(0); // terminate program
} // end try
catch (IOException ioException)
System.err.println("Error processing file.");
System.exit(1);
} // end catch
finally
try
if (file != null)
file.close(); // close file
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end finally
} // end method createFile
} // end class CreateRandomFile-------------------------------------------------------------------------------------------------
// Exercise 14.11: CreateRandomFileTest.java
// Testing class CreateRandomFile
public class CreateRandomFileTest
// main method begins program execution
public static void main( String args[] )
CreateRandomFile application = new CreateRandomFile();
application.createFile();
} // end main
} // end class CreateRandomFileTest-------------------------------------------------------------------------------------------------
// Exercise 14.11: MenuOption.java
// Defines an enum type for the hardware credit inquiry program's options.
public enum MenuOption
// declare contents of enum type
PRINT(1),
UPDATE(2),
NEW(3),
DELETE(4),
END(5);
private final int value; // current menu option
MenuOption(int valueOption)
value = valueOption;
} // end MenuOptions enum constructor
public int getValue()
return value;
} // end method getValue
} // end enum MenuOption-------------------------------------------------------------------------------------------------
// Exercise 14.11: FileEditor.java
// This class declares methods that manipulate hardware account records
// in a random access file.
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
import org.egan.RandomAccessHardwareRecord;
public class FileEditor
RandomAccessFile file; // reference to the file
Scanner input = new Scanner(System.in);
// open the file
public FileEditor(String fileName) throws IOException
file = new RandomAccessFile(fileName, "rw");
} // end FileEditor constructor
// close the file
public void closeFile() throws IOException
if (file != null)
file.close();
} // end method closeFile
// get a record from the file
public RandomAccessHardwareRecord getRecord(int recordNumber)
throws IllegalArgumentException, NumberFormatException, IOException
RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
if (recordNumber < 1 || recordNumber > 100)
throw new IllegalArgumentException("Out of range");
// seek appropriate record in a file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.read(file);
return record;
} // end method getRecord
// update record tool name in file
public void updateRecordToolName(int recordNumber, String newToolName)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Record does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.setToolName(newToolName);
record = new RandomAccessHardwareRecord(
record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
record.write(file); // write updated record to file
} // end method updateRecordToolName
// update record in file
public void updateRecordQuantity(int recordNumber, int newQuantity)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Record does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.setQuantity(newQuantity);
record = new RandomAccessHardwareRecord(
record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
record.write(file); // write updated record to file
} // end method updateRecordQuantity
// update record in file
public void updateRecordCost(int recordNumber, double newCost)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Record does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.setCost(newCost);
record = new RandomAccessHardwareRecord(
record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
record.write(file); // write updated record to file
} // end method updateRecordCost
// add record to file
public void newRecord(int recordNumber, String toolName, int quantity, double cost)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() != 0)
throw new IllegalArgumentException("Record already exists");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record = new RandomAccessHardwareRecord(recordNumber, toolName, quantity, cost);
record.write(file); // write record to file
} // end method newRecord
// delete record from file
public void deleteRecord(int recordNumber) throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Account does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
// create a blank record to write to the file
record = new RandomAccessHardwareRecord();
record.write(file);
} // end method deleteRecord
// read and display records
public void readRecords()
RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
System.out.printf("%-10s%-15s%-15s%10s\n","Record","Tool Name","Quantity","Cost");
try // read a record and display
file.seek(0);
while (true)
do
record.read(file);
while (record.getRecordNumber() == 0);
// display record contents
System.out.printf("%-10d%-15s%-15d%10.2f\n",record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
} // end while
} // end try
catch (EOFException eofException) // close file
return; // end of file was reached
} // end catch
catch (IOException ioException)
System.err.println("Error reading file.");
System.exit(1);
} // end catch
} // end method readRecords
} // end class FileEditor-------------------------------------------------------------------------------------------------
// Exercise 14.11: TransactionProcessor.java
// A transaction processing program using random-access files.
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.egan.RandomAccessHardwareRecord;
public class TransactionProcessor
private FileEditor dataFile;
private RandomAccessHardwareRecord record;
private MenuOption choices[] = {MenuOption.PRINT, MenuOption.UPDATE, MenuOption.NEW,
MenuOption.DELETE, MenuOption.END};
private Scanner input = new Scanner(System.in);
// get the file name and open the file
private boolean openFile()
try // attempt to open file
// call the helper method to open the file
dataFile = new FileEditor("hardware.dat");
} // end try
catch (IOException ioException)
System.err.println("Error opening file.");
return false;
} // end catch
return true;
} // end method openFile
// close file and terminate application
private void closeFile()
try // close file
dataFile.closeFile();
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end method closeFile
// create, update or delete the record
private void performAction(MenuOption action)
int recordNumber = 0; // record number of record
String toolName; // tool name of the hardware instrument
int quantity; // total amount of items
double cost; // hareware tool price
int choice; // choose an update option
int newRecordNumber; // the updated record number
String newToolName; // the updated tool name
int newQuantity; // the updated quantity
double newCost; // the updated cost
try // attempt to manipulate files based on option selected
switch(action) // switch based on option selected
case PRINT:
System.out.println();
dataFile.readRecords();
break;
case NEW:
System.out.printf("\n%s%s\n%s\n%s","Enter record number,",
"tool name, quantity, and cost.","(Record number must be 1 - 100)","? ");
recordNumber = input.nextInt(); // read record number
toolName = input.next(); // read tool name
quantity = input.nextInt(); // read quantity
cost = input.nextDouble(); // read cost
dataFile.newRecord(recordNumber, toolName, quantity, cost); // create new record
break;
case UPDATE:
System.out.print("\nEnter record number to update (1 - 100): ");
recordNumber = input.nextInt();
record = dataFile.getRecord(recordNumber);
if (record.getRecordNumber() == 0)
System.out.println("Record does not exist.");
else
// display record contents
System.out.printf("%-10d%-12s%-12d%10.2f\n\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
System.out.printf("%s%s","\nEnter 1 to update tool name, ",
"2 to update quantity, or 3 to update cost : ");
choice = input.nextInt();
if (choice == 1)
System.out.print("Enter new record tool name : ");
newToolName = input.next();
dataFile.updateRecordToolName(recordNumber,newToolName); // update record
// tool name
// retrieve updated record
record = dataFile.getRecord(recordNumber);
// display updated record
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
else if (choice == 2)
System.out.print("Enter new record quantity : ");
newQuantity = input.nextInt();
dataFile.updateRecordQuantity(recordNumber,newQuantity); // update record
// quantity
// retrieve updated record
record = dataFile.getRecord(recordNumber);
// display updated record
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
else if (choice == 3)
System.out.print("Enter new record cost : ");
newCost = input.nextDouble();
dataFile.updateRecordCost(recordNumber,newCost); // update record cost
// retrieve updated record
record = dataFile.getRecord(recordNumber);
// display updated record
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
} // end else
break;
case DELETE:
System.out.print("\nEnter an account to delete ( 1 - 100): ");
recordNumber = input.nextInt();
dataFile.deleteRecord(recordNumber); // delete record
break;
default:
System.out.println("Invalid action.");
break;
} // end switch
} // end try
catch (NumberFormatException format)
System.err.println("Bad input.");
} // end catch
catch (IllegalArgumentException badRecord)
System.err.println(badRecord.getMessage());
} // end catch
catch (IOException ioException)
System.err.println("Error writing to the file.");
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input.nextLine();
} // end catch
} // end method performAction
// enable user to input menu choice
private MenuOption enterChoice()
int menuChoice = 1;
// display available options
System.out.printf("\n%s\n%s\n%s\n%s\n%s\n%s","Enter your choice",
"1 - List hardware records", "2 - Update a hardware record",
"3 - Add a new hardware record", "4 - Delete a hardware record", "5 - End program\n?");
try
menuChoice = input.nextInt();
catch (NoSuchElementException elementException)
System.err.println("Invalid input.");
System.exit(1);
} // end catch
return choices[menuChoice - 1]; // return choice from user
} // end enterChoice
public void processRequests()
openFile();
// get user's request
MenuOption choice = enterChoice();
while (choice != MenuOption.END)
performAction(choice);
choice = enterChoice();
} // end while
closeFile();
} // end method processRequests
} // end class TransactionProcessor-------------------------------------------------------------------------------------------------
// Exercise 14.11: TransactionProcessorTest.java
// Testing the transaction processor.
public class TransactionProcessorTest
public static void main(String args[])
TransactionProcessor application = new TransactionProcessor();
application.processRequests();
} // end main
} // end class TransactionProcessorTest-------------------------------------------------------------------------------------------------
Below is the sample data to be entered into the random input file hardware.dat :
Record Tool Quantity Cost
Number Name
3 Sander 18 35.99
19 Hammer 128 10.00
26 Jigsaw 16 14.25
39 Mower 10 79.50
56 Saw 8 89.99
76 Screwdriver 236 4.99
81 Sledgehammer 32 19.75
88 Wrench 65 6.48Message was edited by:
egan128
Message was edited by:
egan128
Message was edited by:
egan128Hi Does anyone know if I can modify the record number
in the random access file hardware.dat for each
hardware record each time and update it in
hardware.dat to display it?If the "record number" is data that is stored in the file, then you can modify it. More precisely: it is possible to modify it.
The rest of the question had too many incompatible verbs for me to understand it.
Also why does it say
"Record does not exist" if I modify the record number
for a hardware and try to update it but could not
find that record?"Record does not exist" is a fairly reasonable error message for the situation where a program looks for a record but cannot find it. Are you asking why that particular lump of code actually does that?
(One thousand lines of code removed) -
Who knows how to record data in the file that after recording, it will not be'abrakadabra', but very distinctive
files for example with integer.
Thank you in advanceSave as strings:
DataOutputStream.writeUTF(String) -
Parsing xml from a socket stream
Hi,
I'm working on a client/server program, and I have the following problem. I'd like the client to send an xml-string to the server, and then the server to parse it (using SAX). The problem is, I cannot get the server to work.
I thought the following would work, but it doesn't:
InputSource xmlIn = new InputSource(socket.getInputStream());
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser xmlReader = factory.newSAXParser();
DefaultHandler handler = new MyHandler(); //
xmlReader.parse(xmlIn, handler);
The setup now is, that the user of the client program can type something in the command line, press enter and the string is then sent to the server, which should parse it, but doesn't (instead gives a nullpointer exc.)
Does anybody know how to parse an incoming string like this?
thnx in advance,
KSThe parser expects to read to the end of the stream. If you closed the stream right after you wrote to it, I bet it would work. You wouldn't want to close the stream though would you? Try sending the string using a DataOuputStream and calling DataOutputStream.writeUTF(String) on the client side. Then, on the server side call String str = in.readUTF() (where 'in' is a DataInputStream). Then wrap the string in a StringReader and give the StringReader to the parser as it's input source.
Maybe you are looking for
-
How to restrict records in Infoset query
Hi Friends, I have created an Infoset & a query based on this infoset. I would like to restrict certain records being displayed, based on field value, say if field A = 'Blank' I do not want to see this record on the Bex report. Please let me know i
-
Hello adept SBO I have installed SBO 8.8 in windows Seven, but sometimes i got some issues like oppening,... brief SBO is not stable. I am using SBO8.8 with SQL Server 2005 and 2008 R as license Sql server and windows 7? I wonder if this troubles are
-
Dear Experts, As per my client scenerio, They have A vendor Who is a service provider and he provides raw material also. Can I creat or extend in two Vendor account groups (ie DOME & SERV)? Plz help Regards, Mehul
-
Message security while using JMS
Hello, In PI7.0 we are using JMS adapter to pull data from another MQ system. How can we make this call secure? I mean, during data transfer using FTP or HTTP, we can use FTPS or HTTPS. In case of JMS, is there any way in which message security can b
-
Error in Sandbox solution webpart
I am getting this error on the page sometime. SharePoint object [SPContentDatabase Name=Content_237364] is in an unsupported state, and could not be used by the current farm. Server stack trace: at Microsoft.SharePoint.Administration.SPPersistedUp