Writing binary data to file ???
Hi all,
I am facing a strange problem in my java program. Please go through the following code...
import java.io.*;
public class Hex2BinFile
Hex2BinFile()
boolean hex2bin(String source,String destFile)
try
PrintWriter opGif = new PrintWriter ( new FileWriter(destFile, false));
int strlen = source.length();
for ( int i = 0; i < strlen; i += 2)
opGif.print((char)Integer.parseInt(source.substring(i, i+2), 16));
opGif.flush();
opGif.close();
catch(Exception e)
System.out.println(e);
return false;
return true;
public static void main(String [] args)
Hex2BinFile hbf = new Hex2BinFile();
hbf.hex2bin("05", "/home/oracle/1.bin"); // resulting file size is 1 byte
hbf.hex2bin("AF", "/home/oracle/2.bin"); // resulting file size is 2 byte
This is a very simple class. In this class hex2bin() function takes hex string, and then convert it to binary value (character by character) and write binary value to a specified file.
In the above mentioned code, in main() method, i am calling hex2bin() method twice.
In the first call the result is satisfactory and a file (1.bin) is created with file size 1 byte as i am passing one byte hex value to this function.
But in the second call to hex2bin(), I am also passing 1 bye hex value, and resulting file size is 2 bytes. I also observe that when I pass a value greater than '7F' hex, the resulting file size is two byte.
What is the cause of this inconsistancy? is there any error or problem? and what is the solution? Please guide me.
Thanks in advance...
Thank u very much,
FileOutputStream opGif = new FileOutputStream(destFile, false);
I have changed above line with the following line:
PrintWriter opGif = new PrintWriter ( new FileWriter(destFile, false));
and now this code is working very fine.
Thanks once again...
Similar Messages
-
Writing binary data to a file without carriage returns every 512 bytes
Is there a VI for writing binary data to a file without carriage returns being inserted every 512 bytes?
ThanksHi Momolxg,
I could be way off on this. I tried to simulate what you've done by
making a for loop that would run a set number of times. For my example I
used 1025. I wired the iteration terminal to a 'Write to SGL File.vi'
outside the loop with indexing enabled. It wrote the SGL data from 0 to
1024 to the file. I then read the file with a 'Read Characters from
File.vi' and searched the output for a carriage return (0D hex). It was
found five times. The reason why was the SGL number it was reading had a
13 (0D hex) in it. Perhaps you're running into a similar problem?
I tried it again, this time using the 'Write to I16 File.vi'. The
carriage return was found five times: the 28th character the first time
then on the 512th character four consecutive time
s after that. I suppose
that makes sense that you'd find a 0D in the numbers at equal spacings if
they're incrementing this way... In this case the carriage returns you're
seeing are actually numbers from your data.
One big difference is that I'm using a set pattern of numbers. This
doesn't appear to be your case. Is there a better way we can duplicate
your problem? It sounds interesting. Again my simulation could be way
off. (I'm also running this on LV60 for Linux so my results could be
different)
- Kevin
In article <[email protected]>,
"momolxg" wrote:
> Is there a VI for writing binary data to a file without carriage returns
> being inserted every 512 bytes? Thanks -
Exception writing binary data to the output stream to client -Broken pipe
Hi,
I am trying to use the drag & drop feature using Contributor mode of Webcenter sites. Single Image Page Attribute is working properly where as Multiple Image Page Attribute throws the following error:
[ERROR] [.kernel.Default (self-tuning)'] [logging.cs.satellite.request] Exception writing binary data to the output stream to client 10.191.117.106
java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at weblogic.servlet.internal.ChunkOutput.writeChunkTransfer(ChunkOutput.java:568)
at weblogic.servlet.internal.ChunkOutput.writeChunks(ChunkOutput.java:539)
at weblogic.servlet.internal.ChunkOutput.flush(ChunkOutput.java:427)
at weblogic.servlet.internal.ChunkOutput$2.checkForFlush(ChunkOutput.java:648)
at weblogic.servlet.internal.ChunkOutput.write(ChunkOutput.java:333)
at weblogic.servlet.internal.ChunkOutputWrapper.write(ChunkOutputWrapper.java:148)
at weblogic.servlet.internal.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:148)
at COM.FutureTense.Servlet.ServletRequest$OutputOutputStream.write(ServletRequest.java:80)
at COM.FutureTense.Servlet.ServletRequest.write(ServletRequest.java:1633)
at com.openmarket.Satellite.RequestContext.write(RequestContext.java:1123)
at com.openmarket.Satellite.BytePiece.stream(DataPiece.java:253)
at com.openmarket.Satellite.CacheObjectImpl.stream(CacheObjectImpl.java:651)
at com.openmarket.Satellite.Http11Responder.respondForWrapper(Http11Responder.java:142)
at com.openmarket.Satellite.WrapperAwareResponder.respond(WrapperAwareResponder.java:36)
at com.openmarket.Satellite.SatelliteServer.execute(SatelliteServer.java:85)
at com.openmarket.Satellite.servlet.BaseServlet.doGet(BaseServlet.java:118)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at com.fatwire.wem.sso.cas.filter.CASFilter.doFilter(CASFilter.java:557)
at com.fatwire.wem.sso.SSOFilter.doFilter(SSOFilter.java:51)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3730)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3696)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2273)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1490)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
Thanks
KarthiKThank u very much,
FileOutputStream opGif = new FileOutputStream(destFile, false);
I have changed above line with the following line:
PrintWriter opGif = new PrintWriter ( new FileWriter(destFile, false));
and now this code is working very fine.
Thanks once again... -
Pueden decirme para que se utiliza writing waverform data to file
me encontre con un pdf que habla acerca de filtros y menciona mucho writing waverform data to file y especificamente no se para que se utiliza podrian ayudarme ezplicandome su uso y en donde lo puedo conseguir?.
muchas gracias.Pues se utiliza para guardar datos en un archivo de forma que se pueden leer despues para poner en un grafico o analyzar de cualquier forma.
Existen varios typos de archivos y entonces varios VIs para guardar datos, creo que uno esta con los "Express VIs" y los otros se encontran el la "palette" Files.
Espero que le ayude.
When my feet touch the ground each morning the devil thinks "bloody hell... He's up again!" -
Writing binary data to ASP file from applet through URLConnection
Hi Everybody,
I am facing a proble with HttpURLConnection.I want to write some binary data from applet to an ASP file.The other end ASP file read this binary data and process , Here problem is I have opened URLConnection to the page and Created OutputStream and writing byte by Write() method But other end we are not getting bytes...we are not getting error too at java side..can any body help me..do we need to set any property to URLConnection...here I am giving sample code...
OutputStream os;
URL uConnect2;
HttpURLConnection hucConnect2;
uConnect2= new URL("http://webserver/vnc/sendtoserver.asp?"); hucConnect2=(HttpURLConnection)uConnect2.openConnection();
hucConnect2.setDoOutput(true);
hucConnect2.setRequestMethod("POST")
os=new DataOutputStream(hucConnect2.getOutputStream());
os.writeBytes("Hello");
Thanks in Advance
MadhavDo you remember to flush() and close() the stream?
-
Writing binary data in same format as with FORTRAN code
Hello,
I would like to write out data in a binary format that is used by FORTRAN unformatted direct access files. I have some code in FORTAN that produces the correct format; however, I have been unable to reproduce the output with a Java method.
The FORTAN code to write an array Z is:
REAL Z(72,46,16)
OPEN(8,FILE='grads.dat',FORM='UNFORMATTED',
& ACCESS='DIRECT',RECL=72*46)
IREC=1
DO 10 I=1,16
WRITE (8,REC=IREC) ((Z(J,K,I),J=1,72),K=1,46)
IREC=IREC+1
10 CONTINUE
The Java code I was able to come up with to write out an array arrTS produces binary data differently:
FileOutputStream fosOut = new FileOutputStream(filename,false);
for(int x=0; x<this.xmax; x++) {
for(int y=0; y<this.ymax; y++) {
ByteArrayOutputStream bosOut = new ByteArrayOutputStream(2);
DataOutputStream dos = new DataOutputStream(bosOut);
dos.writeFloat((float)this.arrTS[x][y]);
byte[] arrByte = bosOut.toByteArray();
fosOut.write(arrByte);
fosOut.close();
Any help is greatly appreciated.
Best regards,
StefanI am using a software to read in the data that I am calculating in Java. I cannot easily change the format that software is reading; therefore, ASCII is not an option.
The software that reads the data states something about "Little-endian". Do you which Java classes to use for that?
Best regards,
Stefan
First, you need to find out the format of yourFORTRAN
output. Is it ASCII? EBCDIC? BCD? IEEE?
Big-endian? Little-endian?
Until you know that you won't know which Javaclasses
to use.Also I wouldn't be too sure different FORTRAN
compilers use the same data format.
In my view the best system interchange format still is
the ASCII text file. Why don't you let the Fortran
program use it to write its data to file. It should be
no problem reading it from Java. -
Hi,
I'm trying to develop a JSP that returns binary data in the form of a jpeg image.
I found this on google where one of the replies correctly states that to be compliant I need to use XML JSPs:
http://www.caucho.com/quercus/faq/question.xtp?question_id=1005
This is what I am now doing but I am getting exceptions about:
"java.lang.IllegalStateException: getOutputStream() has already been called for this response"
I have traced this to be on the very last line of the blah_jsp.java file created by tomcat:
"if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);".
My code looks like this:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2">
<jsp:directive.page contentType="image/jpeg" />
<jsp:declaration><![CDATA[ .... ]]></jsp:declaration>
<jsp:scriptlet><![CDATA[
try {
updateImage();
response.getOutputStream().write( apodImageData );
} catch (Exception e) {
out.println( e.toString() );
StringWriter sr = new StringWriter();
e.printStackTrace( new PrintWriter( sr ) );
out.println( sr.toString() );
]]></jsp:scriptlet>
</jsp:root>
Any ideas? Is there a way to stop the container produced java file from tampering with out? Obviously my code is working but the final line of the container produced code is failing because I've manually been using result.getOutputStream().
Any ideas?Have just found this after many hours of searching:
http://www.mooreds.com/weblog/archives/000018.html
The upshot is that TC4 is non compliant in this area, TC5 is fixed.. -
What's the fastest C function for writing binary data to disk?
I'm acquiring data at high speeds across multiple boards and I'm having a hard time writing the data to disk fast enough to keep up. I'm programming in C in Visual Studios and I'm currently using fwrite. I have a similar system set up in LabView and my C code can't perform as well. Is there a better or faster way to write to disk in C?
Some speculated a few years ago that there would be
no reason to use Fortran too. :)Are you saying there's a reason to use Fortran? Help me lord!
Anyway, they were right! The industry may be stalling, but the vision is not. The economy and many other factors are to blame for why we haven't been able to break out of the computing paradigm we're stuck in. It's like the automobile, it hasn't changed in a century. Why? $$$
Oh, people said we'd have flying cars by now, where are they? Well we do have them! But we're too busy spending that 400 billion a year on war instead of evolving as a species.
Anyway, when we take the next step and have true distributed computing with multi-core processors everywhere, Java will run, Java will scale, and Java will outperform ANYTHING available.
And speaking of game programming, the PS3 developers are having a hell of a time doing the 3 CPUs. Why? Because all they've ever done is single & double processor systems. It's time to think out of the box. When a game console hits the market with 512 CPU cores, do you REALLY think C/C++ will run on that? But, Java was designed for it.
Java = the future
C++ = the past -
How to handling Binary data and File operation?
Hello Everyone,
I think this question might have been asked a lot of time but I was unable to find one solution so, please help needed in this from all you guys..
I am creating a byte[] of the media files of mp4, and jpg, using the below code,,
File ff = new File(filename);
fos = new FileOutputStream(ff);
int b;
byte[] f = this.getMediaFile();
for (b = 0; b < f.length; b++) {
if (f[b] != -1) {
fos.write(f);
fos.flush();
fos.close();
After i convert it i have to store it in the MySql Database as BLOB object, for retrieving byte[] from the database is simple i can do that also successfully with this code.java.sq.Blob obj = (java.sql.Blob) rs.getBlob("file");
InputStream is = null;
ByteArrayOutputStream bc = null;
is = obj.getBinaryStream();
bc = new ByteArrayOutputStream();
int b;
while ((b = is.read()) != -1) {
System.out.print(b + " ");
bc.write(b);
Now the real problem is that when i want to recreate a mp4 audio or video file i am unable to do so, the file created is smaller in size and also it doesn't get played in windows default player nor VLC. I am able to get the image file of jpg format using the BufferedImage & ImageIO.writer();
How do i do for mp4 file, have no clue for that.
Pleases help out with this.
Thanks..if (f[b] != -1) {I don't get that line. What if you try to output the data without that condition, like this:
fos = new FileOutputStream(ff);
byte[] f = this.getMediaFile();
for (int b = 0; b < f.length; b++) {
fos.write(f);
fos.close(); -
URGENT PLEASE HELP WRITING BINARY DATA
I'm attaching a jsp page to download an excel file (generated using HSSF) that doesn't work. When I open t.xls in Excel it looks fine. I think the problem is with out.write.
<%@ page import="java.io.*" %>
<%
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=output.xl
s");
String fn="/tmp/t.xls";
File fnam=new File(fn);
FileInputStream fis=null;
response.setContentLength((int) fnam.length());
int iRead;
try{
fis= new FileInputStream(fn);
while((iRead=fis.read()) != -1) {
out.write(iRead);
out.flush();
} catch (IOException i) {
out.println("ioexception");
%>Because there is a newline between the page import line and the <% before the code...
<%@ page import="java.io.*" %><%
response.setContentType("application/vnd.ms-excel");
... -
Wrting zip Data using File adapter
Did any one tried or implemented writing zip/gz file using File adapter.
I know how to write opaque data using Base64Binary. But i am not getting on how to use file adapter for writing zip file.
Any help / suggestions are greatly appreciated.
Thanks !!Thanks for the reply, have been using opaque for a while now and know the read & write for that.
My problem is i am not able to get how i can write compressed data , writing binary data is fine i can use string->encode->base64binary->opaque and can write that.
But that will not be the compressed form.
Thanks !! -
Hi all I have a basic doubt. How does Servlets is preferred technology to generate binary data than JSP? Any limitation in JSP?
Okay,
When you write a JSP file, you type it in text, and all the text you type is sent to the client that requests your page. Everything is sent including carriage returns, spaces, tab characters and anything you have type into the file. Only things that are inside <% and %> do not get sent through. If you have several blank lines at the end of the file they will be sent to the client and may cause issues if you are writing binary data that needs to be handled by an application.
With Servlets you have to write data to the outputstream you get from the (cant quite remember) response.getOutputStream() method. This ensures that only what you want to send gets sent to the client.
It sepends on what you need it for. If it doesnt matter what you send through then JSP can be used to write binary data. In one application I had to send through sound files to the client and any extra data would only corrupt the sound, so it had to be sent using servlets.
Does that help? -
Data plug-in for binary data with byte streams of variable length
Hi there,
I would like to write a data plug-in to read binary data from file and I'm using DIAdem 10.1.
Each data set in my file consists of binary data with a fixed structure (readable by using direct access channels) and of a byte stream of variable length. The variable length of each byte stream is coded in the fixed data part.
Can anyone tell me how my data plug-in must look like to read such kind of data files?
Many thanks in advance!
Kind regards,
StefanHi Brad,
thank you for the very quick response!
I forgot to mention, that the data in the byte stream can actually be ignored, it is no data to be evaluated in DIAdem (it is picture data and the picture size varies from data set to data set).
So basically, of each data set I would like to read the fixed-structure data (which is the first part of the data set) and discard the variable byte stream (last part of the data set).
Here is a logical (example) layout of my binary data file:
| fixedSize-Value1 | fixedSize-Value2 | fixedSize-Value3 (=length of byte stream) | XXXXXXXXXXXXX (byte stream)
| fixedSize-Value1 | fixedSize-Value2 | fixedSize-Value3 (=length of byte stream) | XXXXXX (byte stream)
| fixedSize-Value1 | fixedSize-Value2 | fixedSize-Value3 (=length of byte stream) | XXXXXXXXXXXXXXXXXXXX (byte stream)
What I would like to show in DIAdem is only fixedSize-Value1 and fixedSize-Value2.
´
If I understood right, would it be possible to set the BlockLength of each data set by assigning Block.BlockLength = fixedSize-Value3 and to use Direct Access Channels for reading fixedSize-Value1 and fixedSize-Value2 ?
Thank you!
Kind regards,
Stefan -
Storing binary data to a file......
Hi Friends,
I am trying to make a webapp in which users can upload Videos and I can store that videos on the server. I have this bit of code:
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
VideoUploadForm myForm = (VideoUploadForm)form;
// Process the FormFile
FormFile myFile = myForm.getTheFile();
byte[] fileData = myFile.getFileData();
}My question is, should i store the byte array into some text file???Then how can i read it back and get the original format i.e *.avi or *.mpg.
This might be easy,but this is my first time dealing with binary data,so your help would be appreciated.
Thanks
P.S: Any links would be appreciatedThanks BalusC,
After lots of hardwork finally I am trying to upload the binary file in the database,but getting this error:
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, file_blob) values(1, 1, 'uploaded file from user', _binary'\0\0�!\0\0�\' at line 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1571)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1666)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2994)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:936)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:773)
at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.execute(DelegatingPreparedStatement.java:168)This is my code thats trying to write that binary file:
public class StoreData {
private static Log log = LogFactory.getLog(StoreData.class);
private static final String INSERT_BLOB = "Insert into videos.files (id, owner_id, desc, file_blob)" +
" values(1, 1, 'uploaded file from user', ?)";
public void WriteData(VideoUploadForm myForm){
log.info("Writing file to database");
Connection conn = ConnectionUtil.getConnection();
PreparedStatement stmt = null;
// Process the FormFile
FormFile myFile = myForm.getTheFile();
byte[] bytes = null;
try{
bytes = myFile.getFileData();
}catch(IOException ie){
log.error("Upload File not Found");
ie.printStackTrace();
InputStream is = new ByteArrayInputStream(bytes);
try {
stmt = conn.prepareStatement(INSERT_BLOB);
stmt.setBinaryStream(1,is,bytes.length);
stmt.execute();
stmt.close();
}catch (Exception e) {
log.error("Error writing data to file:");
e.printStackTrace();
} finally {
ConnectionUtil.closeStatement(stmt);
ConnectionUtil.closeConnection(conn);
}Looking for some help here..... -
How to read a file with both text and binary data?
For text data I use a BufferedReader,
for binary data I use a DataInputStream.
Since readLine is deprecated in DataInputStream, how can I read in a proper way a file that contains some lines of text followed by some binary data.
Is there a way to do this without writing a new 'readLine' for DataInputStream (that has to take into account the different newlines for Unix en other OS's)?sorry about that ^
NEW STRING str
WHILE there is stuff in the file DO
getByte()
IF reading a string THEN
WHILE byte is not a return character DO
convert the byte to character/string
append char to str
WEND
ELSE IF reading raw data THEN
parse raw data
do stuff with it
END IF
WEND
Maybe you are looking for
-
Hi i have a ipod touch my old email no longer works how can i swap emails
can i swap old email for new
-
Browsing the library in Finder. Is there a logical way to do it?
Hi All, I am an iPhoto 7 user who has just upgraded to Aperture. A friend of mine has just brought my attention to the fact that the database format used by Aperture (and newer versions of iPhoto) is not easily browsable via Finder. What I mean by th
-
I have used PE in various versions for years. Most of this year I've used PE7 which works perfectly on my PC, the only reason I upgraded to PE8 was to use the Effects Mask facility. This is the only reason, and now I have to say I so exasperated I'm
-
Because of a time clock change, I now have to use an Airlink101 AR504 Router off of my DSL instead of the WRT54g that i've been using for months. Is there any way to cascade the WRT54G off of the AR504 so that i can still have teh wireless network w
-
I have a desktop PC that I built which has the following: Intel GT-R Extreme Core I-7 4.4 Ghz Crucial M4 256 SATA III SSD Main Drive with WD VelociRaptor WD4500 10,000 RPM HDD 850W power supply MSI R5770 Hawk Radeon 1Gb 129-bit GDDR5 PCI express vide