Java.nio read/write question
Hello,
I just started to learn the java.nio package so I decided to make a simple Echo server. I made a client which reads a line from the keyboard, sends it to the server and the server returns it. It all works except one little detail. Here's little code from the server:
int n = client.read(buffer);
if ( n > 0)
buffer.flip();
client.write(buffer);
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
charBuffer = decoder.decode(buffer);
System.out.println(charBuffer.toString());
buffer.clear();
}So that works, I send the data and then I receive it back. But only for the client. I also wanted the server to print the line which is the reason for the charset and the decoder. The above code however prints only a blank line. Thus I tried this:
int n = client.read(buffer);
if ( n > 0)
buffer.flip();
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
charBuffer = decoder.decode(buffer);
System.out.println(charBuffer.toString());
client.write(buffer);
buffer.clear();
}Or in other words I just moved the write() part downwards. So far so good, now the server was actually printing the lines that the client was sending but nothing was sent back to the client.
The question is how to make both, the send back line and the print line on the server side to work as intended. Also a little explanation why the events described above are happening is going to be more than welcome :)
Thanks in advance!
Strike notice
A number of the regular posters here are striking in protest at the poor
management of these forums. Although it is our unpaid efforts which make the
forums function, the Sun employees responsible for them seem to regard us as
contemptible. We hope that this strike will enable them to see the value
which we provide to Sun. Apologies to unsuspecting innocents caught up in
the cross-fire.
Similar Messages
-
I'm so sorry if this has been asked, but here I go anyways. I got my iBook G4 as a gift a bit over a year ago, therefore I didn't really have any control over certain situations. My CD drive does not allow me to burn [write] DVDs. I know this is because it was bought without that feature. Is there anyway to send my iBook to Apple and have them replace my drive with a DVD read/writer? How expensive would this be? Would it just be cheaper to buy and external one from LaCie? Thank you so much for any info!
No doubt it would be cheaper to add an External like a Lacie or one from any number of manufactures
You can if you choose have a new CD/DVD Drive and burner installed and there are several different vendors that will do this for you or you can do it your self.
http://www.mcetech.com/?gclid=CPzAh92mg4YCFQqQJAod-kVOhw
Here is one, but there are literaly hundreds of places that do this.
Don -
Hard drive read/write question
Hi,
I purchased this mac pro(2008) with the stock seagate 320gb hard drive (model ST3320820AS_P) and I am interested to know what kind of read write numbers to expect from this drive.
I am having a tough time trying to find any numbers that aren't in reference to RAID setups, and became concerned that this drive might be working at peak performance due to firmware issues others are talking about.
(tangent - I would like to add more drives, but am on the fence for WD or seagate)
System Info
Xbench Version 1.3
System Version 10.5.2 (9C31)
Physical RAM 2048 MB
Model MacPro3,1
Drive Type ST3320820AS_P
Sequential 92.82
Uncached Write 70.70 43.41 MB/sec [4K blocks]
Uncached Write 110.35 62.43 MB/sec [256K blocks]
Uncached Read 82.04 24.01 MB/sec [4K blocks]
Uncached Read 129.89 65.28 MB/sec [256K blocks]
Random 33.16
Uncached Write 11.33 1.20 MB/sec [4K blocks]
Uncached Write 73.50 23.53 MB/sec [256K blocks]
Uncached Read 88.77 0.63 MB/sec [4K blocks]
Uncached Read 134.04 24.87 MB/sec [256K blocks]http://www.barefeats.com/hard94.html
http://www.barefeats.com/quad07.html
http://www.barefeats.com/quad08.html
750GB WD SE16 $168 is hard to beat.
I saw some systems came with WD 320GB. Guess Apple is using both for now. -
Hello Everyone, nice to see a large Flex user group.
I am a beginner to flex and I have a simple question. I am
currently writing a web application in Flex. I compute some data
and all I want to do is take this string and write it to a file on
the local disk. In other words, writing some data to a location on
the disk. Please note that this is a web application. I did some
searching and could not find anything that works...since it is a
flex web application they have some tight security. I am guessing
we might need some help from javascript or something but do not
know how to do that. If anyone could help me with this it would be
really helpful. Thanks.This is correct - web apps cannot write to the local disk.
Imagine you went to a web site that has a banner SWF and that SWF
was written to open a file on your disk and fill up your disk
drive. Or perhaps worse, the SWF opens a file and reads your
personal and financial information. You just cannot be sure what is
going to happen when you visit a web site. So we made the Flash
Player as secure as possible and removed the ability to read or
write local files.
AIR, on the other hand, does not have that restriction. So
you might want to look into that if writing to the local disk is
important. -
Newbie socket read write question
Hello all,
I need to develop a simple client application in java using socket
programming. The client will connect to a server implemented in VC++.
The server part has been implemented so I need to develop only the
client part.
Could anybody help me with a simple program that sends data to the
server and then prints out whatever the server sends back for the
given request.
The client and the server communicate using a specified format of bytes as shown below. I do not know how to read those bytes using the sizes as the token.
I know how to connect to the server but I do not know the proper way of sending and receiving data.
connection = new Socket(destination, port);
outStream = new DataOutputStream connection.getOutputStream());
//send the ID 1 to the server
outStream.writeByte(1);
//send the total packet size
//send the data
Thanks in advance
Pertheli
The client and server communicates with the following packet format
shown below. Each packet will have header, size and data as shown
PACKET
offset(byte) contents
0 byte PACKET ID
1 byte PACKET length (motolora format)
2 byte
3 byte DATA * n (motolora format)
4 byte
5 byte ~ DATA
n byte
Now for a For say PACKET ID = 1
we send the data to the server like
0 byte (motolora format)
3 byte
Then from the VC server we recieve the data in the format such as
0 byte Name
43 byte
44 byte StatusHi!
Try this...
Socket connection = new Socket(server,port);
// use a Buffered*Stream as often as possible, because
// of the IP Packet Lengths...It Increases the
// network performance (but you DON'T need it)
// you'll send bytes or messages to the server in
// the OutputStream and receive answers from the
// server in the InputStream
int packetOutputBufferSize = connection.getSendBufferSize();
int packetInputBufferSize = connection.getReceiveBufferSize();
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream(),packetOutputBufferSize);
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream(),packetInputBufferSize);
// sending data through the socket
// create your packet in a byte array
byte[] output = new byte[<packet-lenght>];
output[0]=<packet ID>
output[1]=....
bos.write(output,0,output.length);
// receiving data from the socket
byte[] input = new byte[<max-packet-length>];
int read=0;
int length=0;
while ((read=bis.read(input,length,(input.length-length)) > 0) {
length+=read;
if (length>=input.length) break;
// now your server output is in the bytearray 'input'
If it isn't possible to set a max packet size, use a bytearray as buffer and write it content into a ByteArrayOutputStream, thats something like a resizable write-only byte array. (you'll get the full content of it by calling the method ByteArrayOutputStream.toByteArray())
Maybe you want to check the packet content during receiving the bytes from the socket: Then you should use some read() method from the InputStream, but thats not very powerful. -
Java NIO - reading large amount of data
Hi,
I have diffuculties of reading large amount of data with SocketChannel (using directAllocated buffer & allocated one). Files greater than 300KB are cut even though I tried write the data into FileChannel.
My Code:
ByteBuffer directBlockBuffer = ByteBuffer.allocateDirect(150000);
buffer = ByteBuffer.allocate(6000000);
out = new FOS("d:\\msgData.tmp");
fc=out.getFOS().getChannel(); // FileChannel
int fileLength = (int)fc.size();
while (clientChannel.read(directBlockBuffer)>0)
{ directBlockBuffer.flip() buffer.put(directBlockBuffer);
directBlockBuffer.compact();
//close data file
buffer.flip();
fc.write(buffer);
fc.close();
FOS.close();
// end of code
Any ideas?
Thanks
ASTI don't understand how the "write" result will help read the whole data.
Anyway, I changed the code so the SocketChannel will read in smaller chunks (~8KB) & the FileChannel writes in every read
but the data stream is cut again (to ~5KB no matter what size of file I send).
In the updated code when try to compare socketChannel.read to -1 I got endless loop.
I'm basically trying to write POP3/SMTP server program, this part of code handles attachment that is received by the SocketChannel in one unit (i.e 1+ MB of data, the other SMTP commands/lines are no more than 27 chars and simple to handle).
Therefore I need to be ready to accept large amount of data to the buffer & write it to filechannel. (In the POP3 thread I'm using MappedByteBuffer successfully).
Updated code:
ByteBuffer directBlockBuffer = ByteBuffer.allocateDirect(8192);
while (clientChannel.read (directBlockBuffer>0&&directBlockBuffer.hasRemaining))
directBlockBuffer.flip();
fc.write(directBlockBuffer);
directBlockBuffer.clear();
}I think based on API my code is logical (and good for small files) but what about handling bigger files (up to 5MB)?
Thanks,
AST -
NEW Excel Read/Write Lib for JAVA
FastExcel is a pure java excel read/write component.It's FAST and TINY. provide:
* Reading and Writing support for Excel '97(-2003) (BIFF8) file format.
* Low level structures for BIFF(Binary Interchange File Format).
* Low level structures for compound document file format (also known as "OLE2 storage file format" or "Microsoft Office compatible storage file format").
* API for creating, reading excel file.
website http://fastexcel.sourceforge.net/
Edited by: guooscar on Jun 18, 2009 7:44 PMguooscar wrote:
cotton.m wrote:
guooscar wrote:
I read almost all of jxl source code and i try to use it to export/import data the result is slow,OOM,that’s allOkay, fair enough.= _ =|||?
At best this is a pretty specialized tool right? I mean 300,000,000 rows of data imported or exported (and I'm not sure which) daily from/to Excel is a bit of a wtf.
But without formula support... it's sort of like the difference between a SAX and DOM parser. -
Java app is writing question marks instead of extended characters
People,
since I've installed an Sun E3000 with Solaris9 I'm having problems with accents (extended characters) in my java application: - it writes question marks instead of accents.
This machine used to be Solaris 2.6 and we formatted/installed Solaris9 and got the problem since then.
My application uses a thin driver to connect to Oracle9i database, and via unix I can call sqlplus and insert chr(199) and SELECT it (�) with no problems, but application writes ? in nohup.out.
If you can point me in any direction, please let me know.
Regards, Orlando.I'm pretty sure that the default locale "C" corresponds to the 7-bit US-ASCII character set. Again, this is all the methaphorical shot in the dark, but it's the only time that I've seen this happen. Sun's own documentation says to use something other than C or US ASCII if international or special characters will be needed.
Here is my /etc/default/init for ISO 8859-15.
TZ=US/Eastern
CMASK=022
LC_COLLATE=en_US.ISO8859-15
LC_CTYPE=en_US.ISO8859-1
LC_MESSAGES=en_US.ISO8859-1
LC_MONETARY=en_US.ISO8859-15
LC_NUMERIC=en_US.ISO8859-15
LC_TIME=en_US.ISO8859-15
If the system that you're using can be rebooted, try changing the /etc/default/init file to something like the above, but with the specific for your locale. Obviously, en_US is not your area, but I have no idea what Brazil's would be. -
Which reader & writer should I buy?
HI everyone,
I have done extensive research about java card reader,writer and software kits. I have found three possible devices. can you please help me to decide which one I should buy:
1. MoTechno- http://www.motechno.com/java-card-sdk.0.html
-500 EURO Apprx
http://www.motechno.com/rfid-sdk.0.html
-500 EURO Apprx
2. Gemalto Gemplus RAD SDK Kit for Contact Java Card
-1000 EURO
Gemplus GemPROX SDK Kit for Contactless Java Card
-1000 EurO
3. Giesecke & Devrient : SmartCafe Pro Toolkit -450 Euro
4. JCOP- I have no information about itThanks.
but how do i load the applet onto a card. a reader
would
only allow to read it in response to APDU commands. No. A "reader" (the better name would be "[smart]card terminal") allows you to send APDUs to the card and receive the response-APDUs. What the card does with the data you sent to it depends on the APDU you sent. Some APDUs allow to store data on the card or install an applet. Therefore there are no "reader" on the market which allow to read but not to write to java cards/smart cards.
Jan -
Asynchronous read & write by using Asynchronous api provided in nio-java 7
HI,
I am trying to write a small program to implement **asynchronous read & write by using Asynchronous api provided in nio in java 1.7** in windows machine.
i tried the following code to write a small string to a file asynchronously.file is getting created but the contents are not dispalying.
static long startTime = System.currentTimeMillis();
static long endTime;
static long execTime;
public static void main(String[] args) {
String path = "C:\\AsynchWrite.txt";
Path file = Paths.get(path);
final AsynchronousFileChannel channel;
long pos = 1;
try {
OpenOption[] options = { StandardOpenOption.CREATE,
StandardOpenOption.WRITE, StandardOpenOption.SYNC };
channel = AsynchronousFileChannel.open(file, options);
ByteBuffer buffer = ByteBuffer.allocate(1000);
String writeThis = "Testing by writing a line";
byte[] src = writeThis.getBytes();
buffer.put(src);
channel.write(buffer, pos, null,
new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
System.out.println("completed successfully");
System.out.println("start time :" + startTime);
endTime = System.currentTimeMillis();
System.out.println("end time : " + endTime);
execTime = endTime - startTime;
System.out.println("Execution Time :" + execTime);
System.out.println("Execution Time(ms) :"
+ execTime);
try {
channel.force(true);
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@Override
public void failed(Throwable exc, Object attachment) {
// TODO Auto-generated method stub
System.out.println("failed!!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}Please help me out
Thanks in advance,
RaviIt looks like you are missing buffer.flip() after your put as otherwise the buffer position will be at 25 (not 0 as you expect).
-
Java NIO - copy-on-write buffer
This is regarding peculiar behavior of a Java program on Linux-IA64 platform.
I have a Java program that uses MappedByteBuffer. For the same file, there are three buffers - read only, read/write and copy-on-write (cow)
First, change contents of cow buffer and print all buffers. The change is reflected only in cow buffer (not in ro or rw) - as expected.
Then, change contents of r/w buffer and print all buffers. The change is NOT observed in cow buffer, but reflected in ro and rw buffers (for Linux-IA64). I tried the same program in Linux-X86 and the change is reflected in all buffers (including cow buffer).
I used JDK 1.4.2_03 for compiling and running. The doc for MappedByteBuffer says
"The content of a mapped byte buffer can change at any time, for example if the content of the corresponding region of the mapped file is changed by this program or another. Whether or not such changes occur, and when they occur, is operating-system dependent and therefore unspecified."
Is this behaviour acceptable? Is this observed in any other platform?
I think Java NIO leaves it to the O/S and JVM is not doing anything here (as different from java.io). This could probably result in inconsistent behaviour across platforms (though it improves performance)
Please let me know your thoughts.My thought is that you have posted this to the wrong forum.
-
Read/write Java float[]
I'm looking for the quickest and most effecient way to read/write a float array (float[]) to file in a raw binary fashion.
In C I would do...
float fp = (float )malloc(sizeof(float)*nfloats);
// ... populate fp
int file = open("filename.bin", O_CREAT|O_WRONLY|O_TRUNC);
write(file, (void *)fp, sizeof(float)*nfloats);
close(file);
(forgive the lack of error checking etc. - for explanation purposes only)
So if in Java I have a...
float[] fp;
How dow I read/write fp to a file in a similar way?
Many thanks!The easiest to program is java.net.DataInputStream.readFloat().
The most efficient is probably java.nio.FloatBuffer.get(), followed by java.nio.ByteBuffer.getFloat(). -
ATTN Java Gurus: udf.policy - Unable to Grant Read,Write to Specific File
NOTE: A correct answer to this question will receive the rarely used OTN 25pt <font color="silver" size="3" face="script">Platinum Star</font><font color="silver" size="4" face="script"> ★</font> *
Essbase 9.3.1
Using a Java CDF that reads and writes to a file
I'm trying to grant permission to a specific file in the file system by granting permission in the udf.policy file.
When I uncomment the line permission java.security.AllPermission; the CDF works fine and interacts with the file correctly. This is just to prove that the CDF works, I need to tighten this up to a single file. I stop and start the app after each edit.(I've also tried bouncing the Essbase server too)
When I use the following, I get an exception, shown below. Nothing of consequence is being written to the app or essbase logs
grant {
permission java.io.FilePermission "C:/test/essbase/CalcProfile.db", "write, read";
};java.security.AccessControlException: access denied (java.io.FilePermission C:\esstest\Server\PlugIns\Essbase read)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
at java.security.AccessController.checkPermission(AccessController.java:546)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at java.lang.SecurityManager.checkRead(SecurityManager.java:871)
at com.hyperion.essbase.calculator.ESecurityManager.checkRead(ESecurityManager.java:80)
at java.io.File.exists(File.java:731)
at org.sqlite.Conn.open(Conn.java:98)
at org.sqlite.Conn.<init>(Conn.java:57)
at org.sqlite.JDBC.createConnection(JDBC.java:77)
at org.sqlite.JDBC.connect(JDBC.java:64)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at com.accelatis.essbase.calcprofile.cdf.CalcComment.calcComment(CalcComment.java:16)
>
I've tried creating the policy using PolicyTool, same result. However, I have no idea what or if I should put in the "CodeBase" field.
Has anyone had success creating read & write permissions to a single file using the udf.policy file? What is the magic syntax?
Regards,
Robb Salzmann
* <font face="small" size=".2em" color="silver">right after the platinum star award is created</font>Hi Robb,
Never heard of the OTN 25pt Platinum Star award... It sounds appetizing, but I know I won't get it since I've got no Java experience. :)
I was just gonna ask if you've thought about posting the same question on one of the Java forums?
https://forums.oracle.com/forums/category.jspa?categoryID=285
Cheers,
Mehmet -
Java.util.PropertyPermission * read,write
on tryieng to call my function i am getting this error .
the Permission (java.util.PropertyPermission * read,write)
has not been granted by dbms_java.grant_permission to
SchemaProtectionDomain(JAVA|PolicyTableProxy(JAVA))
what should i do to remove this error.
nulli got it running by executing
DBMS_JAVA.GRANT_PERMISSION('JAVA','SYS:java.util.PropertyPermission', '*', 'read,write')
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Sherry:
on tryieng to call my function i am getting this error .
the Permission (java.util.PropertyPermission * read,write)
has not been granted by dbms_java.grant_permission to
SchemaProtectionDomain(JAVA|PolicyTableProxy(JAVA))
what should i do to remove this error.
<HR></BLOCKQUOTE>
null -
(java.util.PropertyPermission * read,write) has not been granted
I've been getting the following error:
java.security.AccessControlException:
the Permission (java.util.PropertyPermission * read,write)
has not been granted by dbms_java.grant_permission to
SchemaProtectionDomain(ROVER|PolicyTableProxy(ROVER))
So to fix it I did the flowing as system:
SQL> EXEC DBMS_JAVA.GRANT_PERMISSION('ROVER','SYS:java.util.PropertyPermission', '*', 'read,write');
PL/SQL procedure successfully completed.
SQL> COMMIT;
Commit complete.
But their is no change.
What am I missing?
I'm using 8.1.6 on linux.I'm also in this situation:
I got this error:
[1]: (Error): ORA-29532: Java call terminated by uncaught Java exception:
java.security.AccessControlException: the Permission
(java.net.SocketPermission mailhost resolve) has not been granted by
dbms_java.grant_permission to
SchemaProtectionDomain(TOLKIEN|PolicyTableProxy(TOLKIEN)) ORA-06512: at line
14
I believe I must use the dbms_java.grant_permission procedure to grant the
procedure to resolve hostname. But I don't know how to use this procedure.
I tried with
'dbms_java.grant_permission(SchemaOfMyJavaClass,'java.net.SocketPermission',
'mailhost','resolve',intRet);'
and a record is been appended to dba_java_policy, but Oracle complaines again.
Someone can help us?
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Oracle Support():
Can you see the permission in dba_java_policy table?
<HR></BLOCKQUOTE>
null
Maybe you are looking for
-
Report URL call in a procedure
Hi all, I have the following report URL: http://localhost:7778/reports/rwservlet?report=f:\oracle\scott13.rdf&desformat=pdf&destype=cache&userid=wh1/scot@db I want to call this URL in a procedure how can i do this? Any reply would be appriciated. Reg
-
How to interprete db_stats report for -m option
Hi please help me to interprete the db_stats report (for -m option). What is the total number of pages created by DB? (It is "Current page count" or "The number of page allocations"). what is " Total number of times hash chains searched for a page" ,
-
How do you open link to a file contained in a PDF portfolio in a new window?
I am making a large PDF portfolio with one main document that links to other documents contained inside the portfolio. The problem is when I select a link, it will take me to the document I would like it to but I cannot move back to the main document
-
How can i take off the notebook s name
I ve bought my Macbook Pro to another person and now Before to give the macbook to her i need to Take off the name i d given to it. I d like to delete things to macbook start From zero...for new notebook owner Will be able to give another name to it
-
All of a sudden,will not startup (no chime), only sound is the dvd(dl) that is spinning inside. I have tried everything I know (dmc? reset), removing 1 memory module at a time and trying to startup, still no chime only spinning of disk, still disk sp