javascript - onmessage even will not fire using a java server - java

I know this has been asked before, but I have tried all the posts on this site and still no fix so I though I might upload my code and see what im doing wrong.
I am using java for my server and javascript websocket for my client. When I send information from my server to my client nothing happens and also when I send data from client to server nothing is received. Please help?!?!?!
Here is my server code:
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import org.apache.commons.codec.binary.Base64;
public class Server extends JFrame
{
private JTextArea textArea = new JTextArea();
private Scanner fromClient;
private BufferedOutputStream toClient;
private Socket socket;
private static final int TEXT = 1, BINARY = 2, CLOSE = 8, PING = 9, PONG = 10;
public static void main(String[] args)
{
new Server();
}
public Server()
{
setLayout(new BorderLayout());
add(new JScrollPane(textArea), BorderLayout.CENTER);
setTitle("Server");
setSize(700, 400);
setLocation(0, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
try
{
//create server socket
ServerSocket serverSocket = new ServerSocket(8181);
textArea.append( "Starting Server...\n" );
textArea.append("Server started at " + new Date() + '\n');
//Wait for connection
socket = serverSocket.accept();
//create input output
fromClient = new Scanner(socket.getInputStream());
toClient = new BufferedOutputStream(socket.getOutputStream());
this.handle_handshake(fromClient);
textArea.append("\n\nsending text....\n");
//this.brodcast("pop");
this.send_message("test");
int i = 1;
while (true)
{
String s = fromClient.hasNext() ? fromClient.nextLine() : "";
textArea.append("Client: " + s + "\n");
if( i == 0 ) break;
}
socket.close();
serverSocket.close();
}
catch (IOException ex)
{
System.err.println(ex);
}
}
private boolean handle_handshake( Scanner scanner )
{
String line;
String hash_str = "";
String key = "";
int counter = 0;
while ( scanner.hasNextLine() && (line = scanner.nextLine() ) != null )
{
String[] tokens = line.split( ": " );
switch ( tokens[0] )
{
case "Sec-WebSocket-Key":
key = tokens[1].trim();
textArea.append( "SocketKey" );
hash_str = this.get_return_hash( tokens[1] );
break;
case "Sec-WebSocket-Version":
textArea.append( "WebSock-Ver: " + tokens[1] + "\n" );
break;
default:
textArea.append( tokens[0] + ": " + tokens[tokens.length-1] + "\n" );
break;
}
++counter;
if ( counter > 12 )
{
textArea.append( "Handshake" );
String msg = "HTTP/1.1 101 Switching Protocols\r\n";
msg += "Upgrade: websocket\r\n";
msg += "Connection: Upgrade\r\n";
msg += "Sec-WebSocket-Accept: " + hash_str + "\r\n";
msg += "\r\n\r\n";
try
{
toClient.write( msg.getBytes( "UTF-8" ) );
textArea.append( "Server > Client: " + msg );
//toClient.flush();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
textArea.append( "\n\nClosing handshake\n\n" );
return true;
}
}
return false;
}
public void brodcast(String mess) throws IOException
{
byte[] rawData = mess.getBytes();
int frameCount = 0;
byte[] frame = new byte[10];
frame[0] = TEXT;
if(rawData.length <= 125){
frame[1] = (byte) rawData.length;
frameCount = 2;
}else if(rawData.length >= 126 && rawData.length <= 65535){
frame[1] = (byte) 126;
byte len = (byte) rawData.length;
frame[2] = (byte)((len >> 8 ) & (byte)255);
frame[3] = (byte)(len & (byte)255);
frameCount = 4;
}else{
frame[1] = (byte) 127;
byte len = (byte) rawData.length;
frame[2] = (byte)((len >> 56 ) & (byte)255);
frame[3] = (byte)((len >> 48 ) & (byte)255);
frame[4] = (byte)((len >> 40 ) & (byte)255);
frame[5] = (byte)((len >> 32 ) & (byte)255);
frame[6] = (byte)((len >> 24 ) & (byte)255);
frame[7] = (byte)((len >> 16 ) & (byte)255);
frame[8] = (byte)((len >> 8 ) & (byte)255);
frame[9] = (byte)(len & (byte)255);
frameCount = 10;
}
int bLength = frameCount + rawData.length;
byte[] reply = new byte[bLength];
int bLim = 0;
for(int i=0; i<frameCount;i++){
reply[bLim] = frame[i];
bLim++;
}
for(int i=0; i<rawData.length;i++){
reply[bLim] = rawData[i];
bLim++;
}
toClient.write(reply);
toClient.flush();
textArea.append("\n\n\nEnd of brodcasting: " + mess + "\n\n\n");
}
private void send_message( String msg )
{
try
{
textArea.append( "Sending Message: " + msg + "\n" );
byte[] textBytes = msg.getBytes( "UTF-8" );
//ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte code = TEXT;
//opcode
toClient.write( code );
//length
toClient.write( (byte) textBytes.length );
//data
toClient.write( textBytes );
//fin end line
toClient.write( code );
toClient.flush();
}
catch ( IOException e )
{
System.out.printf( "IOE: %s", e.getMessage() );
}
}
private String get_return_hash( String key )
{
textArea.append( "|| " + key + " ||\n" );
String protocol_str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
byte[] sha1_bytes = sha1( key + protocol_str );
String final_hash = new String(Base64.encodeBase64( sha1_bytes ));
return final_hash;
}
private byte[] sha1(String input)
{
try
{
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
return result;
}
catch ( NoSuchAlgorithmException e )
{
return null;
}
}
}
And Here is my client code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="assets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$( document ).ready( function()
{
var ws;
var host = 'ws://localhost:8181';//'ws://echo.websocket.org';
if('WebSocket' in window)
{
console.log( "Connect" );
connect(host);
}
function connect(host)
{
ws = new WebSocket(host);
ws.binaryType = 'blob'; //ws.binaryType = 'arraybuffer';
ws.onopen = function( evt )
{
console.log( "Connection opened" );
console.log( "readyState: " + ws.readyState );
console.log( evt );
console.log('protocol: ' + ws.protocol);
setInterval(test, 5000);
};
ws.onerror = function( evt )
{
console.log( 'Error Code: ' + evt.code );
console.log( evt );
};
ws.onmessage = function (evt)
{
console.log('reveived data:' + evt.data);
};
ws.onclose = function (evt)
{
console.log( "Socket closed" );
console.log( "Reason: " + evt.reason + " Code: " + evt.code );
console.log( "Clean Close: " + evt.wasClean );
};
};
function test()
{
console.log("waiting...");
//var data = str2ab("Ping");
var line = 'waiting...';
// perform some operations on the ArrayBuffer
console.log( ws.readyState );
if (ws.readyState == 1) ws.send(line);
if (ws.bufferedAmount === 0)
{
console.log('SENT!');
}
else
{
console.log('NOT SENT! left over' + ws.bufferedAmount);
}
};
});
</script>
</head>
<body>
</body>
</html>
Thank you for any help!!

The biggest (or at least the first) issue that you can resolve is in the handle handshake.
Change:
msg += "Sec-WebSocket-Accept: " + hash_str + "\r\n";
to:
msg += "Sec-WebSocket-Accept: " + hash_str;
This is causing the handshake to end with three "\r\n". The client ends the handshake after reading the first two, causing the third to get left in the stream. This means your last \r\n will get read in as part of whatever data the client tries to read next. If you try to send the client a message, it will disconnect due to a bad opcode (most likely).

Related

DatagramPacket is accumulating values

I created a chat in Java, which displays the messages sent and received on the screen. The problem is that when sending the message it is picking up the previously sent value. For example, I send the message written "Microsoft", and then I send another message written "Apple", when the display shows "Applesoft", it appears that it is not emptying DatagramPacket. What can be done?
class Recebe implements Runnable {
#Override
public void run() {
byte[] dadosReceber = new byte[255];
boolean erro = false;
DatagramSocket socket = null;
while (true) {
try {
socket = new DatagramSocket(getPorta());
} catch (SocketException ex) {
Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
}
erro = false;
while (!erro) {
DatagramPacket pacoteRecebido = new DatagramPacket(dadosReceber, dadosReceber.length);
try {
socket.receive(pacoteRecebido);
byte[] b = pacoteRecebido.getData();
String s = "";
for (int i = 0; i < b.length; i++) {
if (b[i] != 0) {
s += (char) b[i];
System.out.println("Valor S: " + s + " ");
}
}
// if (!s.equals(new GeraHash().MD5("envie a chave publica!!!"))) {
String nome = pacoteRecebido.getAddress().toString() + " disse:";
notifica(nome + s);
System.out.println("Dados Recebe 2: " + s + " ");
// } else {
// conexaoAtual().envia("Funcionou!");
// System.out.println("Dados Recebe 1: " + s + " ");
// }
} catch (Exception e) {
System.out.println("erro");
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
}
erro = true;
continue;
}
}
}
}
}
socket.receive(pacoteRecebido);
byte[] b = pacoteRecebido.getData();
String s = "";
for (int i = 0; i < b.length; i++) {
if (b[i] != 0) {
s += (char) b[i];
System.out.println("Valor S: " + s + " ");
}
Usual problem. You're ignoring the actual length of the received datagram, given by DatagramPacket.getLength(). You can reduce all that to:
socket.receive(pacoteRecebido);
System.out.println(new String(pacoteRecebido.getData(), 0, pacoteRecebido.getLength());

write a program in java using modbus simulator for reading holding register values

I want to take real-time data using modbus tcp/ip simulator for filling of a tank that uses port no 502.
How can I write a code in java to get the holding register value from the simulator and also I want to control the values of it?
If you use a Modbus library like this one most of the work is already done for you.
ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder("localhost").build();
ModbusTcpMaster master = new ModbusTcpMaster(config);
CompletableFuture<ReadHoldingRegistersResponse> future =
master.sendRequest(new ReadHoldingRegistersRequest(0, 10), 0);
future.thenAccept(response -> {
System.out.println("Response: " + ByteBufUtil.hexDump(response.getRegisters()));
ReferenceCountUtil.release(response);
});
import java.io.* ;
import java.net.* ;
import java.util.*;
public class Modcli {
public static void main(String argv[]) {
if (argv.length < 4) {
System.out.println("usage: java test3 dns_name unit reg_no num_regs");
System.out.println("eg java test3 aswales8.modicon.com 5 0 10");
return;
}
try {
String ip_adrs = argv[0];
int unit = Integer.parseInt(argv[1]);
int reg_no = Integer.parseInt(argv[2]);
int num_regs = Integer.parseInt(argv[3]);
System.out.println("ip_adrs = "+ip_adrs+" unit = "+unit+" reg_no = "+
reg_no+" num_regs = "+num_regs);
// set up socket
Socket es = new Socket(ip_adrs,502);
OutputStream os= es.getOutputStream();
FilterInputStream is = new BufferedInputStream(es.getInputStream());
byte obuf[] = new byte[261];
byte ibuf[] = new byte[261];
int c = 0;
int i;
// build request of form 0 0 0 0 0 6 ui 3 rr rr nn nn
for (i=0;i<5;i++) obuf[i] = 0;
obuf[5] = 6;
obuf[6] = (byte)unit;
obuf[7] = 3;
obuf[8] = (byte)(reg_no >> 8);
obuf[9] = (byte)(reg_no & 0xff);
obuf[10] = (byte)(num_regs >> 8);
obuf[11] = (byte)(num_regs & 0xff);
// send request
os.write(obuf, 0, 12);
// read response
i = is.read(ibuf, 0, 261);
if (i<9) {
if (i==0) {
System.out.println("unexpected close of connection at remote end");
} else {
System.out.println("response was too short - "+i+" chars");
}
} else if (0 != (ibuf[7] & 0x80)) {
System.out.println("MODBUS exception response - type "+ibuf[8]);
} else if (i != (9+2*num_regs)) {
System.out.println("incorrect response size is "+i+
" expected"+(9+2*num_regs));
} else {
for (i=0;i<=2;i++) {
int w = (ibuf[0+i+i]<<8) + ibuf[1+i+i];
System.out.println("word "+i+" = "+w);
}
for (i=3;i<=5;i++) {
int w = (ibuf[i+3]) ;
System.out.println("word "+i+" = "+w);
}
for (i=0;i<num_regs;i++) {
int w = (ibuf[9+i+i]<<8) + ibuf[10+i+i];
System.out.println("word "+i+" = "+w);
}
}
// close down
es.close();
} catch (Exception e) {
System.out.println("exception :"+e);
}
}
}

.dat file in java, how to access it, totally consfused on how to read in from it

So my problem is that, I want to input this list below in a .dat file and read it in but i dont know how, when i tried to do it via a .txt file (instead of .dat) and put it in the project order so i can have inputstream read through it gives me and excpetion
I dont mind using .txt but it gives me this streamcorrupted exception like below
java.io.StreamCorruptedException: invalid stream header: 4C696665
the list its supposed to reading
Life of Pi
Titanic
Tropic Thunder
GoodFellas
Momento
so what i want to do is put the list above in a inventory.dat file but i dont know how?
here is the code,
import java.io.*;
import java.util.StringTokenizer;
public class Main {
static SortedList inventory;
static BufferedReader in;
public static StockItem getStockItem( String title2 )
{
int idx;
StockItem newItem = new StockItem( title2 );
//
// Determine whether the video with the title is in the inventory.
//
idx = inventory.locateIndex( newItem );
if ( idx <= inventory.size() )
{
StockItem oldItem = (StockItem)inventory.get( idx );
if ( oldItem.compareTo(newItem) == 0 )
return oldItem;
}
//
// If not, insert.
//
inventory.sortedAdd(newItem);
return newItem;
}
//
// If the stock item has no information, remove it from the inventory.
//
public static void VerifyStockItem( StockItem item )
{
if ( item.getHave() == 0 && item.getWant() == 0 &&
item.getWaitingList().isEmpty() )
{
inventory.sortedRemove( item );
}
}
public static void cmd_I( String title )
{
StockItem item = getStockItem( title );
System.out.println( item );
VerifyStockItem( item );
}
public static void cmd_L()
{
System.out.println( inventory );
}
public static void cmd_A( String title )
{
StockItem item = getStockItem( title );
System.out.println( "Input the initial want value:" );
while ( true )
{
try {
item.setWant( Integer.parseInt( in.readLine() ) );
break;
}
catch ( IOException e ) {
continue;
}
}
VerifyStockItem( item );
}
public static void cmd_M( String title )
{
StockItem item = getStockItem( title );
System.out.println( "The original want value was " + item.getWant() +
"." );
System.out.println( "Input the new want value:" );
while ( true )
{
try {
item.setWant( Integer.parseInt( in.readLine() ) );
break;
}
catch ( IOException e ) {
continue;
}
}
VerifyStockItem( item );
}
public static void cmd_D()
{
try {
BufferedReader fin =
new BufferedReader( new FileReader( "incoming.dat" ) );
int lines = Integer.parseInt( fin.readLine() );
for ( int i = 0; i < lines; i++ )
{
StringTokenizer st = new StringTokenizer( fin.readLine() );
String title = st.nextToken();
int count = Integer.parseInt( st.nextToken() );
StockItem item = getStockItem( title );
ListReferenceBased waitingList = item.getWaitingList();
System.out.println ( "Arrival: " + title + " x " + count );
while( count > 0 && !waitingList.isEmpty() )
{
Customer p = (Customer)waitingList.removeFirst();
System.out.println( "" + p + " received the video." );
count--;
}
if ( count > 0 ) {
item.setHave( item.getHave() + count );
}
VerifyStockItem( item );
}
}
catch( FileNotFoundException fnfe ) {
System.out.println( "incoming.dat should exist." );
return;
}
catch( IOException e ) {
System.out.println(
"The operation is aborted due to an IO error." );
}
}
public static void cmd_O()
{
Node iter = inventory.getHead();
while ( iter != null ) {
Node next = iter.getNext();
StockItem item = (StockItem)iter.getItem();
int count = item.getWant()
+ item.getWaitingList().size()
- item.getHave();
if ( count > 0 ) {
System.out.println( item.title + ": " + count );
}
iter = next;
}
}
public static void cmd_R()
{
Node iter = inventory.getHead();
while ( iter != null ) {
Node next = iter.getNext();
StockItem item = (StockItem)iter.getItem();
int count = item.getHave()
- item.getWant()
- item.getWaitingList().size();
if ( count > 0 ) {
System.out.println( item.title + ": " + count + " returned" );
item.setHave( item.getHave() - count );
}
VerifyStockItem( item );
iter = next;
}
}
public static void cmd_S( String title )
{
StockItem item = getStockItem( title );
if ( item.getHave() > 0 )
{
item.setHave( item.getHave() - 1 );
System.out.println( title + ": You took one. " +
item.getHave() + " video(s) left." );
}
else
{
System.out.println( title + " is sold out." );
System.out.println( "Write your name please." );
while (true) {
try {
Customer p = new Customer( in.readLine().trim() );
item.getWaitingList().addLast( p );
break;
}
catch( IOException e )
{
continue;
}
}
}
VerifyStockItem( item );
}
public static void main(String[] args)
{
//
// Loading from the inventory.dat
//
try {
FileInputStream fis = new
FileInputStream("inventory.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject();
inventory = (SortedList)o;
}
catch (FileNotFoundException fnfe) {
inventory = new SortedList();
}
catch (Exception e) {
System.out.println(e);
}
in = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String cmdLine;
char cmd;
String arg = "";
System.out.print( "Input a command: " );
try {
cmdLine = in.readLine();
}
catch(Exception e) {
break;
}
if (cmdLine.length() == 0) continue;
//
// parse the command line.
//
cmd = cmdLine.charAt(0);
if ( cmdLine.length() >= 3 ) arg = cmdLine.substring(2);
if ( cmd == 'Q' ) break;
//
// dispatch
//
switch( cmd )
{
case 'H':
System.out.println(
"Help on commands \n" +
"---------------- \n" +
"H (help) \n" +
"I <title> (inquire)\n" +
"L (list)\n" +
"A <title> (add)\n" +
"M <title> (modify)\n" +
"D (delivery)\n" +
"O (order)\n" +
"R (return)\n" +
"S <title> (sell)\n" +
"Q (quit)\n" );
break;
case 'I':
cmd_I( arg );
break;
case 'L':
cmd_L();
break;
case 'A':
cmd_A( arg );
break;
case 'M':
cmd_M( arg );
break;
case 'D':
cmd_D();
break;
case 'O':
cmd_O();
break;
case 'R':
cmd_R();
break;
case 'S':
cmd_S( arg );
break;
}
}
//
// Saving into the inventory.dat
//
try {
FileOutputStream fos = new
FileOutputStream("inventory.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(inventory);
fos.close();
// end try
}
catch (Exception e) {
System.out.println(e);
}
}
}
Well, your problem is that your are mixing Readers (plain text format) and Streams (binary format) in an inappropriate way.
First, you write an object in a file using a FileOutputStream. This save the file in binary format.
FileOutputStream fos = new
FileOutputStream("inventory.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(inventory);
fos.close();
Then, you try to do:
BufferedReader fin = new BufferedReader( new FileReader( "incoming.dat" ) );
int lines = Integer.parseInt( fin.readLine() );
But BufferedReader is made to read from plain text, and not from binary files. There is a special case to use it, that is with new BufferedReader(new InputStreamReader(System.in)). But this is because InputStreamReader transform from binary format (of command line) to plain text ;-)
Regards,
The ObjectInputStream constructor blocks until it completes reading
the serialization stream header. Code which waits for an
ObjectInputStream to be constructed before creating the corresponding
ObjectOutputStream for that stream will deadlock, since the
ObjectInputStream constructor will block until a header is written to
the stream, and the header will not be written to the stream until the
ObjectOutputStream constructor executes. This problem can be resolved
by creating the ObjectOutputStream before the ObjectInputStream, or
otherwise removing the timing dependency between completion of
ObjectInputStream construction and the creation of the
ObjectOutputStream.
javaspecs

Why does this image not display correctly when I put it through my HTTP server?

I wrote the following HTTP server:
import processing.net.*;
import java.io.FileInputStream;
import javax.activation.MimetypesFileTypeMap;
Client client = null;
Server server = null;
MimetypesFileTypeMap mimeMap = new MimetypesFileTypeMap();
void setup()
{
server = new Server(this, 80);
println(1);
size(700, 700);
fill(0);
mimeMap.addMimeTypes("application/bmp bmp BMP Bmp");
}
void draw()
{
background(255);
while ( (client = server.available ()) == null) {
}
println(2);
String req = "";
String fileN;
byte[] fileC;
while (client.available () != 0) {
req += client.readString();
try {
Thread.sleep(100);
}
catch (Throwable t) {
}
}
println(req);
fileN = URLDecoder.decode(req.split(" ")[1].substring(1));
if (!fileN.equals("")) {
try
{
FileInputStream fileS = new FileInputStream("C:\\" + fileN);
fileC = new byte[fileS.available()];
fileS.read(fileC);
server.write(
concatSB(
"HTTP/1.0 200 OK\r\nContent-Type: " +
mimeMap.getContentType(fileN.substring( fileN.lastIndexOf("/") + 1 )) +
"\r\nContent-Length: " +
fileC.length +
"\r\n\r\n",
fileC
)
);
println(3);
println(fileN);
}
catch (Exception e)
{
server.write("HTTP/1.0 404 Not Found\r\n".getBytes());
println(fileN + ": " + e.toString());
}
}
exit();
}
void mouseClicked()
{
server.stop();
exit();
}
private byte[] concatSB(final String strng, final byte[] bytes) {
final StringBuilder sb = new StringBuilder(strng);
for (byte b : bytes) {
sb.append((char)b);
}
println(strng);
return sb.toString().getBytes();
}
It works quite well for text, but when I sent this BMP:
I got this BMP out, which opened automatically in Paint:
When I converted the original to a GIF in Paint, the result was not readable through the server and in IE, I got the bad image icon (red X);
How can I fix this?
I do not think that it is a good idea passing fileC which is binary through a StringBuilder. I would rather do something like this:
server.write(
"HTTP/1.0 200 OK\r\nContent-Type: " +
mimeMap.getContentType(fileN.substring( fileN.lastIndexOf("/") + 1 )) +
"\r\nContent-Length: " +
fileC.length +
"\r\n\r\n"
);
server.write(
fileC
);

how to read vb random access file in java

I write vba macros, that create file in random access mode:
Private Type Record
id As Long
name As String * 20
status As String * 10
End Type
Private rec As Record
Private rows_count As Long
Private datfilePath As String
Private Sub writeButton_Click()
datfilePath = ThisWorkbook.Path + "\data\datfile.dat"
datfile = FreeFile()
Open datfilePath For Random As #datfile Len = Len(rec)
rows_count = Int(LOF(datfile) / Len(rec))
rec.id = rows_count + 1
rec.name = "test_name_" + Str(rows_count + 1)
rec.status = "test_sta" + Str(rows_count + 1)
Put #datfile, rows_count + 1, rec
rows_count = Int(LOF(datfile) / Len(rec))
Close #datfile
End Sub
how to read created file in java?
in result:
import java.io.*;
class ReadVBFile {
public static void main(String[] args) throws IOException{
try
{
String file = "datfile.dat";
RandomAccessFile fh = new RandomAccessFile(file,"r");
int file_length =(int)fh.length();
int rec_length = 34;
int rec_count = (int)(file_length/rec_length);
System.out.println("file_length: " + file_length + "\r\n");
System.out.println("rec_count: " + rec_count + "\r\n");
for( int i_row=0; i_row < rec_count; i_row++ )
{
byte[] id_array = new byte[4];
byte[] name_array = new byte[20];
byte[] status_array = new byte[10];
for( int i=0; i < 34; i++ )
{
byte b = fh.readByte();
if( i < 4 )
{
id_array[i] = b;
}
else if( i < 24 )
{
name_array[i-4] = b;
}
else if( i < 34 )
{
status_array[i-24] = b;
}
fh.seek( i_row*34 + i + 1 );
}
// Long as Int
int myInt = ((id_array[1] & 0xff) << 24) | ((id_array[2] & 0xff) << 16) | ((id_array[3] & 0xff) << 8) | (id_array[0] & 0xff);
String name_value = new String(name_array);
String status_value = new String(status_array);
System.out.println( myInt + ", '" + name_value + "', '" + status_value + "'");
}
}
catch(IOException e)
{
System.out.println( "IOException: " + e.getMessage() );
}
catch(Exception e)
{
System.out.println( "Exception: " + e.getMessage() );
}
}
}

Categories