Creating Binary Files in Java
Does anyone know how to create a binary file in Java.
in C i can do an fopen("filename" , "rb") i cannot find a equivalent java binary file stream.
Thanks
The following code is part of my FileIO applet. This method allows the user to download any file from my server and save it on his/her disk, the download is accomplished by doing a byte-read and byte-write (byte mover as I'd call it). This example illustrates how you can read and write binary files in Java:
public void aok_DownLoad(String inputFile, String outputFile) {
try {
URL url=new URL(inputFile);
InputStream in;
in=url.openStream();
BufferedInputStream reader=new BufferedInputStream(in,4096);
FileOutputStream out=new FileOutputStream(outputFile);
BufferedOutputStream writer=new BufferedOutputStream(out,4096);
byte[] buf=new byte[4096];
int byteRead;
while ((byteRead=reader.read(buf,0,4096))>=0) {writer.write(buf,0,byteRead);}
reader.close();
writer.flush();
writer.close();
catch (Throwable exception) {
exception.printStackTrace();
}V.V.
PS: in this posting the code is posted in a different manner so that the > sign is not converted to & gt ; by the forum's software
Similar Messages
-
Creating XML file from Java Bean
Hi
Are there any standard methods in Java 1.5 to create XML file from java bean,
i can use JAXB or castor to do so,
But i would like to know if there is any thing in java core classes,
I have seen XMLEncoder, but this is not what i want.
Any ideas
AshishMarshall JavaBean to an XML document with JAXB or XMLBeans.
-
To read a text file i used
FileReader reader=new FileReader("d:/a.txt");
please guide me on how to read a binary file in java
Any input would be greatly appreciated!
Thanks in advance!
Edited by: nikkj on Aug 7, 2010 7:36 PMI'll give you the quick answer: you use Readers for character streams (e.g., text files) and InputStreams for binary streams (e.g., binary files).
Still, read the tutorial. You will find out lots of useful info. -
How to run .jar on linux & how to create .jar file using java?
hi, may i know how to run .jar on linux & how to create .jar file using java? Can u provide the steps on doing it.
thanks in advance.Look at the manual page for jar:
# man jar
Also you can run them by doing:
# java -jar Prog.jar -
Want To create Zip file using java,And Unzip without Java Program
I want to create a zip text file using java, I know Using ZipOutputStream , we can create a zip file, , But i want to open that zip file without java program. suppose i use ZipOutputStream , then zip file is created But for unZip also difftrent program require. We cant open that zip file without writing diff java program.
Actually i have one text file of big size want to create zip file using java , and unzip simply without java program.Its Possible??
Here is one answer But I want to open that file normal way(
For Exp. using winzip we can create a zip file and also open simply)
http://forum.java.sun.com/thread.jspa?threadID=5182691&tstart=0Thanks for your Reply,
I m creating a zip file using this program, Zip file Created successfully But when im trying to open .zip file i m getting error like "Canot open a zip file, it does not appear to be valid Archive"
import java.io.*;
import java.util.zip.*;
public class ZipFileCreation
public static void main (String argv[])
try {
FileOutputStream fos = new FileOutputStream ( "c:/a.zip" );
ZipOutputStream zip = new ZipOutputStream ( fos );
zip.setLevel( 9 );
zip.setMethod( ZipOutputStream.DEFLATED );
// get the element file we are going to add, using slashes in name.
String elementName = "c:/kalpesh/GetSigRoleInfo092702828.txt";
File elementFile = new File ( elementName );
// create the entry
ZipEntry entry = new ZipEntry( elementName );
entry.setTime( elementFile.lastModified() );
// read contents of file we are going to put in the zip
int fileLength = (int)elementFile.length();
System.out.println("fileLength = " +fileLength);
FileInputStream fis = new FileInputStream ( elementFile );
byte[] wholeFile = new byte [fileLength];
int bytesRead = fis.read( wholeFile , 0 /* offset */ , fileLength );
// checking bytesRead not shown.
fis.close();
// no need to setCRC, or setSize as they are computed automatically.
zip.putNextEntry( entry );
// write the contents into the zip element
zip.write( wholeFile , 0, fileLength );
zip.closeEntry(); System.out.println("Completed");
// close the entire zip
catch(Exception e) {
e.printStackTrace();
} -
Hi all,
Please can anybody tell how to crate a Binary file in Java? because I have to convert a MP3 file into a binary file and store it into a Database as binary value.
Thanks in advance
-Nelsonjwenting wrote:
paulcw wrote:
An MP3 file is already in a binary format.
Binary basically just means "not text".strictly speaking a text file is also binary, in that it's in the end just a stream of bits interpreted in a specific way :)It's like saying "animal" as opposed to "human". Strictly speaking, humans are a subset of animals, but when people say "animal" they usually mean the set of animals minus the set of humans. -
Need to create a function to receive binary files from Java WebDynpro
Hey,
I need to recieve files from java Webdynpro and save them as a file on the backend
system. After that, the file will be loaded to the documentum.
In a function module, I only can get the files as a String. Therefore (I think), I need the
binary file as base64 encoded. Otherwise I can´t get it as a string.
Now I need to decode it in the backend, but how? I know, there are HTTP-classes
in newer system, but not in the 4.6C System, I have here.
Any idea, how I can recieve the files in the function module and transfer it as binary
file to the backend system?
If I load a file from the gui with gui_upload, I get the binary file as an internal table
and can transfer it to the backend filesystem now. Maybe I can get the binary file
in this way in the function?
Thank You for Your help!
Arnehttp://jakarta.apache.org/commons/net/
-
DE PDP-1 binary file from Java
Can someone here help me, please!?
Anyone know how to convert a Java class file into a binary file that will run natively on my Digital PDP-1 computer? I just spent over $120,000 for it! Thanks.
This resurrected thread was first posted November 25, 1960 at 8:25AM
-------------------------------------------------------------------------This resurrected thread was first posted November 25,
1960 at 8:25AMIn what time zone? -
I m not able to create xml file in Java Project
hi all,
I have created one java project just to try with Ant Builder. I have created one class inside it. and now i m creating an XML file inside that project.
But as soon as i try to create the File -> New -> File and give the .xml extention of the file this gives error into the project.
Will you suggest me the solution for that?
Thanks in advance.Assuming that you are facing this problem in NDS, here is the solution.
Go to Windows--> Preferences --> WorkBench -->File Associations
In the File Types list select *.xml
This will display the default associated XML editor as
XML Editor(default) in the bottom list box.
Click on add button near the bottom list box and select Text Editor, click Ok.You will see one more entry in the list box as "Text Editor".
Select this entry and click on the default button.
Click Ok and close the preferences dialogue.
Now create a new xml file.You wont see the error this time.
Please note that this will treat all simple xml files you will create as TEXT Files and always open with Text Editor.You can override this behaviour with right click on the file and select appropriate editor from the "Open With" context menu.
The error you are talking about is because the XML editor tries to check well-formedness and basic syntax rules for the file that you newly created, actually is a noce feature of the IDE.
Rgds,
Amol -
Hi all i am working to create a XML file using java can any one show me some sample code how to do so
All I suggested was to insert a single line ("X.serialize(root);") into your code. Anyway, here's a ready-to-compile source code based on yours. This code utilizes the Xerces-J class library.import java.io.File;
import java.io.FileWriter;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Element;
public class Test {
public static void main(String[] arguments) {
FileWriter out;
DocumentImpl d;
Element root;
XMLSerializer X;
try {
System.out.println(" creatin ");
File fos = new File("xsr.xml");
out = new FileWriter("xsr.xml");
System.out.println("created File .." + fos.getName());
out.flush();
d = new DocumentImpl();
System.out.println("create root");
root = d.createElement("abc");
System.out.println("creating element");
d.insertBefore(root, null);
//out.write(d.createAttribute(""));
OutputFormat o = new OutputFormat(d);
System.out.println("Output format...");
o.setIndent(5);
o.setIndenting(true);
o.setDoctype("lab1.dtd", "lab1.dtd");
o.setDoctype("name of dtd file", "name of dtd file");
X = new XMLSerializer(o);
X.setOutputCharStream(out);
X.serialize(root);
out.flush();
out.close();
catch (Exception e1){
e1.printStackTrace();
} -
Somebody tell me how to create setup file for the software which is made by using java programming. We can create jar file for that purpose but I want to create setup file or exe file.
open source
- izpack (windows, linux, macos) www.izforge.com or org
- nsis.sf.net (winblows only)
commercial
- www.zerog.com 's InstallAnywhere -
Creating .jnlp files from .java files
Last resort: Ask on the forums. I'm having a lot of trouble creating .jnlp files with only a .java file. For some reason if I do create project, the project does not run correctly, but when I make the file and run the file alone, it works perfectly fine. Most of the tutorials that I have read online ask me to do weird manifest .class stuff (in order to make JAR files, which i have failed to do even after attempting to make one after 3 hours). And still, when it comes to make the .jnlp file, I don't quite understand anything. When putting it on the web, I'm planning not to use php (html is in my mind right now), and I have aborted every single attempt at making the JAR files and whatnot.
At this point, I'm not asking for anything other than a link to a tutorial that actually works, because all that I have tried (for the JAR files, especially) have been giving me errors. By the way, one really bothersome output that comes up is the "illegal option: j" when I use the Tool for the JAR file, and I have no idea what that means--I google it and find nothing. The .java itself extends JPanel, so it isn't really an applet.
How to: Run an Applet
Create an Applet Class by clicking File > New > File > File Type > Java Classes > Applet Class.
Enter a name and path for the applet and click Finish.
Build the file by pressing F7.
Create an Applet HTML file by clicking File > New > File > File Type > Other > HTML Applet.
Enter a name and path for the applet and click Finish.
Open the HTML file in JCreator and modify the applet tag to match the name of the applet class.
Open the Project Settings window and select the HTML file as the Run parameter.
Click the Run Project button.It isn't really a code, but I tried doing this and the HTML Applet said code = ".class" Again, I don't have a class for the file. And when you do the "File > New > File > File Type > Java Classes > Applet Class," you get the .java file and a folder that says "components, with two classes in it. I was completely befuddled.http://forum.java.sun.com/thread.jspa?messageID=9783924
-
hi
I am a bit new to java and am having some problems with binary files. What I need to do is search a binary file for any accurances of the data contained with in another set of binary files. I need to know if the first file contains any of the signatures in the set of files. any help would be great.
thanks very much
Colinyou take your file, you read in some bytes and you loop thru those bytes to find matching bytes that you are looking for. Here's some cdoe that's probably not as elegant as it could be, but you get what you pay for.
public static int indexOf(byte[] a, byte[] b) {
return indexOf(a, b, 0);
public static int indexOf(byte[] a, byte[] b, int start) {
if(a == null || b == null || a.length == 0 || b.length == 0 || a.length < b.length) {
return -1;
outer: for(int i = start; i < a.length-b.length; i++) {
if(a[i] == b[0]) {
for(int j = 0; j < b.length; j++) {
if(a[i+j] != b[j]) {
break outer;
return i;
} -
Can't create log file with java.util.logging
Hi,
I have created a class to create a log file with java.util.logging
This class works correctly as standalone (without jdev/weblogic)
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
public class LogDemo
private static final Logger logger = Logger.getLogger( "Logging" );
public static void main( String[] args ) throws IOException
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String dateStr = dateFormat.format(date);
String logFileName = dateStr + "SEC" + ".log";
Handler fh;
try
fh = new FileHandler(logFileName);
//fh.setFormatter(new XMLFormatter());
fh.setFormatter(new SimpleFormatter());
logger.addHandler(fh);
logger.setLevel(Level.ALL);
logger.log(Level.INFO, "Initialization log");
// force a bug
((Object)null).toString();
catch (IOException e)
logger.log( Level.WARNING, e.getMessage(), e );
catch (Exception e)
logger.log( Level.WARNING, "Exception", e);
}But when I use this class...
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.XMLFormatter;
public class TraceUtils
public static Logger logger = Logger.getLogger("log");
public static void initLogger(String ApplicationName) {
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String dateStr = dateFormat.format(date);
String logFileName = dateStr + ApplicationName + ".log";
Handler fh;
try
fh = new FileHandler(logFileName);
fh.setFormatter(new XMLFormatter());
logger.addHandler(fh);
logger.setLevel(Level.ALL);
logger.log(Level.INFO, "Initialization log");
catch (IOException e)
System.out.println(e.getMessage());
}and I call it in a backingBean, I have the message in console but the log file is not created.
TraceUtils.initLogger("SEC");why?
Thanks for your help.I have uncommented this line in logging.properties and it works.
# To also add the FileHandler, use the following line instead.
handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandlerBut I have another problem:
jdev ignore the parameters of the FileHandler method .
And it creates a general log file with anothers log files created each time I call the method logp.
So I play with these parameters
fh = new FileHandler(logFileName,true);
fh = new FileHandler(logFileName,0,1,true);
fh = new FileHandler(logFileName,10000000,1,true);without succes.
I want only one log file, how to do that? -
What the best way to create XML files from JAVA application?
Hi to all,
I need to edit and to create new filex in format of xml. I know to parse, but what would be the best way to do:
1. - Create new file, create like simle text file, or there is some clases that know to do it in more simple way
2.a - Edit XML file, to take some data and add it to the XML in the place I want to.
2.b - Also Edit, but not to add fields, just update some of them.
Code examples or links to samples woul be welcomed.
Best regards, Nick.I have tried working with XML directly using the Java classes but this was a pain. I then looked at DOM4J and JDOM and found JDOM easier to use.
Maybe you are looking for
-
t:jscookmenu is not working in Jboss portlet.
hi.. i am facing a problem in <t:jscookmenu>, that is , i am using the JBoss portlet 2.4 and my aim is to provide a top menu in the default index page.i tried with <t:jscookmenu> , but it is throwing error(scroll down for error code), but <t:outputte
-
I basically got this phone about 2 weeks ago and i cannot download or update anything . I would mind it asking for my sisters apple password but she doesn't know it so how do i take it off ? It will ask for mine then a few seconds later it will ask f
-
PLEASE HELP...how do i exit a programme
I am having some trouble with a programme i have been coding - I am fairly new to Java and have a quick query! How would i exit my programme in the middle of my code... eg if (a = 5) System.out.println("you win"); else ...rest of code!EG I would like
-
I'm using OSX 10.7.3 and have an issue about viewing folder windows. My Finder preference is set to "Always open folders in a new window." That works fine, however, when I open a new folder window I want it on top of, or in front of, the previous w
-
Errors in modifying existing structure...
Hi Friends, I have inserted a field into the existing Z structure and when i am trying to activate that structure, it gives errors like the below fields positions have been changed. Please note that i am not changing the table. It is a structure only