Creating a file from a Java Program
Hi all,
if I want to store a byte array to a file somewhere in the middle of my program... is it possible to create the file inside my Java program, i.e. the file will be created during the execution of my program, and then write this byte array into it? The name of the file to be created is predefined by me, and not thru user input.
If so, does anyone have a sample source code to show me? or redirect me to somewhere ?
Thanks in advance!
Joe
You can take a look at the File, FileOutputStream, FileInputStream classes. A simple one will be like:
byte[] ar = {12,13,14};
File file = new File("wee.dat");
if (!file.exists())
try
FileOutputStream fos = new FileOutputStream(file);
fos.write(ar);
}catch (IOException io){}
else
...
Similar Messages
-
How to compile and run a .java file from another java program
hello,
can any one tell me how to compile and run a *.java* file from another java program which is not in same directory?Well a smarter way of implementing this is by using a solution provided by Java Itself.
If you are using J2SE 6.0+ there is an in built solution provided along with JDK itself and inorder to go ahead with solution the below are set of API which you;d be using it for compiling Java Programs (Files)
http://java.sun.com/javase/6/docs/api/javax/tools/package-summary.html
How do i do that ??
Check out the below articles which would help you of how to do that
http://www.ibm.com/developerworks/java/library/j-jcomp/index.html
http://www.javabeat.net/javabeat/java6/articles/java_6_0_compiler_api_1.php
http://books.google.com/books?id=WVbpv8SQpkEC&pg=PA155&lpg=PA155&dq=%22javax+tools%22+compiling+java+file&source=web&ots=XOt0siYe-f&sig=HH27ovuwvJgklIf8omTykUmy-eM
Now once we are done with compilation.In order to run a Specific class all you ought to do is create an object and its specific methods of a specified class included in the CLASSPATH which you can manage it easily by usage little bit reflections.
Hope that might help :)
REGARDS,
RaHuL -
How can I execute a batch file from my java program
Hi,
Can someone help me or direct me to a link,
How can I execute a DOS batch file from my java program?
ThanksYou will need to grab a handle to the process's
outputstream so u can see its output.The OP didn't mention any output from any batch file;
nor any input for that
matter,so lets not complicate matters here for now
ok?Actually I think this is essential to see whether it works or not. It's either that or do some manual check to see whether it ran, which is not exactly elegant, and in some cases this may not be easier than simply writing the output stream code, or in fact it may be impossible to check manually.
I'm sure it wasn't intentional that your post appeared to be bristling with attitude. -
How to invoke the .bat(batch file ) from the java program
i want to run some commands when i run one java program.
I wrote those dos commands on the batch file and i want to include the bat file in the java program so that i can execute the bat file when i run the java program.
tell me the way that i can run my bat file inside the java program.i tried this :
a .bat file named test.bat, with this code : copy test.bat test2.bat
a java class, Test.class, in the same directory
public class Test {
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd /c test.bat");
proc.waitFor();
int exitVal = proc.exitValue();
System.out.println("Process exitValue: " + exitVal);
catch (Throwable t) {
t.printStackTrace();
} -
How to send a file from a java program to a servlet and get a response
Hi,
How can I call a servlet from a standalone java program and send a file to a servlet using POST method and in return gets the status back from the servlet. Any help is appreciated any small sample will help.
Thanks.Hi,
I am trying the following sample I got from net and am getting the following error. Any help what I am doing wrongs:
06/12/24 02:15:58 org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null
06/12/24 02:15:58 at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:294)
06/12/24 02:15:58 at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:268)
06/12/24 02:15:58 at mypackage9.Servlet1.doPost(Servlet1.java:38)
06/12/24 02:15:58 at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
06/12/24 02:15:58 at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
06/12/24 02:15:58 at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
06/12/24 02:15:58 at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
06/12/24 02:15:58 at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:663)
06/12/24 02:15:58 at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:330)
06/12/24 02:15:58 at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:830)
06/12/24 02:15:58 at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:285)
06/12/24 02:15:58 at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:126)
06/12/24 02:15:58 at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
06/12/24 02:15:58 at java.lang.Thread.run(Thread.java:534)Here is the sample client code:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class PostAFile {
private static String url =
"http://192.168.0.17:8988/Vulcan_Materials-ServletPost2-context-root/servlet/Servlet1";
public static void main(String[] args) throws IOException {
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
client.setConnectionTimeout(8000);
File f = new File("C:\\load.txt");
System.out.println("File Length = " + f.length());
postMethod.setRequestBody(new FileInputStream(f));
int statusCode1 = client.executeMethod(postMethod);
System.out.println("statusLine>>>" + postMethod.getStatusLine());
postMethod.releaseConnection();
}Here is the sample servlet code:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import java.util.List;
import java.util.Iterator;
import java.io.File;
public class Servlet1 extends HttpServlet
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
public void init(ServletConfig config) throws ServletException
super.init(config);
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
try
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
java.util.Enumeration e= request.getHeaderNames();
while (e.hasMoreElements()) {
String headerName=(String)e.nextElement();
System.out.println(headerName +" = "+request.getHeader(headerName));
//System.out.println("Content Type ="+request.getContentType());
DiskFileUpload fu = new DiskFileUpload();
// If file size exceeds, a FileUploadException will be thrown
fu.setSizeMax(1000000);
List fileItems = fu.parseRequest(request);
Iterator itr = fileItems.iterator();
System.out.println("***************************");
while(itr.hasNext()) {
FileItem fi = (FileItem)itr.next();
//Check if not form field so as to only handle the file inputs
//else condition handles the submit button input
if(!fi.isFormField())
System.out.println("\nNAME: "+fi.getName());
System.out.println("SIZE: "+fi.getSize());
//System.out.println(fi.getOutputStream().toString());
File fNew= new File("C:\\", fi.getName());
System.out.println(fNew.getAbsolutePath());
fi.write(fNew);
else
System.out.println("Field ="+fi.getFieldName());
out.println("SUCCESS123456: ");
out.close();
catch(Exception e)
e.printStackTrace();
}Any help on what is wrong.
Thanks -
How to create .exe file of the java program you create?
This must be the qustions asked several time on the forums.So here it is again.
This sounds absurd to some developers here cause you'll say just create jar file and distributre to usr but sometimes there is not possiblity of having runtime environment in windows computers.So if we can bundle the enviroment and the setup together then packing into exe and then distribute like most of commercial java application sounds better.But the problem is how to do that?
Ok creating exe will increase the size but that doesn't matter,if there is any freeware tool to accomplish just that?Check this out:
http://search.java.sun.com/search/java/index.jsp?qp=%2B
orum%3A31&nh=10&qt=create+exe+file+program&col=javaforu
s -
How do I run an exe file from a java program?
I need to run an exe program from within a java program.
what do I need to do this?
thanksSee java.lang.Runtime.exec()
-
How do I call another exe file from a Java program?
Hi,
I am doing a simple IDE (text editor/interpreter) for a simple programming language we are developing. It will be submitted as our project for this semester. I created an exe file (in C) which will be used as the interpreter. How do I call the interpreter from my IDE? The interpreter should run when the user clicks a button (i.e. the "Run" button). I've tried the Java Runtime class but it doesn't work. Anyone who knows how to do it?
Thanks!I first tried to do a simple program that calls system commands such as dir, cd <dir>, etc.
I do not have the exact code right now but as far as I can remember, here's what I wrote:
class Sample{
public static void main(String args[]) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String command;
while ((command = in.readLine()).equalsIgnoreCase("exit") == false){
try{
Runtime.getRuntime().exec(command);
}catch(Exception e){
System.err.println("Error: " + e);
System.exit(0);
} -
Create .xml file from a java file
I wanted to know how can we create a .xml file through java with the given data.
For example: book saler.
data given through java are
1)Sl no
2)Book name
3Book type
4)Book price
i want a xml file generated through the java code
can anyone help me out?i have done like this..
but the problem with this is i want to add more than one book details. i am able to add only one book detais..
package name:createxml
main class:GenerateOrderXml.java
CreateXml.java and order.java
package createxml;
import java.util.Vector;
public class GenerateOrderXml {
public static void main(String[] args) {
try{
Order order= new Order();
CreateXml xml=new CreateXml();
Vector orders=new Vector();
order.setBookName("Java_for_beginers");
order.setAuthorName("Balaguruswamy");
order.setISBN("a123");
order.setNo_of_copies("3");
order.setprice("350");
order.setPublisher("Deepak publishers");
orders.add(0,order);
order.setBookName("Java");
order.setAuthorName("Bala");
order.setISBN("a123");
order.setNo_of_copies("3");
order.setprice("350");
order.setPublisher("Deepak ");
orders.add(1,order);
xml.creatxml(orders);
catch(ArrayIndexOutOfBoundsException e)
e.printStackTrace();
package createxml;
import org.jdom.*;
import org.jdom.output.XMLOutputter;
import java.io.IOException;
import java.util.Vector;
* @author divyashree
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
public class CreateXml {
public void creatxml(Vector orders)
try
Element root = new Element("BookSaler");
Order order= new Order();
order=(Order)orders.elementAt(0);
Element BName = new Element("Bookname1");
BName.setText(order.getBookName());
root.addContent(BName);
Element AName = new Element("Authorname");
AName.setText(order.getAuthorName());
BName.addContent(AName);
Element isbn = new Element("ISBN");
isbn.setText(order.getISBN());
BName.addContent(isbn);
Element price = new Element("Price");
price.setText(order.getprice());
BName.addContent(price);
Element publisher= new Element("Publisher");
publisher.setText(order.getPublisher());
BName.addContent(publisher);
order=(Order)orders.elementAt(1);
Element BName1 = new Element("Bookname2");
BName1.setText(order.getBookName());
root.addContent(BName1);
Element AName1 = new Element("Authorname");
BName1.addContent(AName);
Element isbn1 = new Element("ISBN");
isbn.setText(order.getISBN());
Element price1 = new Element("Price");
BName1.addContent(price);
Element publisher1= new Element("Publisher");
BName1.addContent(publisher);
Document doc = new Document(root);
try {
XMLOutputter serializer = new XMLOutputter();
serializer.setIndent(" ");
serializer.setNewlines(true);
serializer.output(doc, System.out);
catch (IOException e)
System.err.println(e);
}catch(ClassCastException e)
e.printStackTrace();
package createxml;
import java.util.Vector;
public class Order {
protected String ISBN="";
protected String BookName="";
protected String AuthorName="";
protected String No_of_copies;
protected String price;
protected String Publisher="";
public String getISBN()
return this.ISBN;
public String getBookName()
return BookName;
public String getAuthorName()
return AuthorName;
public String getNo_of_copies()
return No_of_copies;
public String getprice()
return price;
public String getPublisher()
return Publisher;
public void setISBN(String isbn)
Vector vec_isbn= new Vector();
ISBN=isbn;
public void setBookName(String bookname)
BookName=bookname;
public void setAuthorName(String authorname)
AuthorName=authorname;
public void setNo_of_copies(String no_of_copies)
No_of_copies=no_of_copies;
public void setprice(String Price)
price=Price;
public void setPublisher(String publisher)
Publisher=publisher;
/***************************************************************************/ -
How to read files on server from a java program?
Hello,
I am fairly new to JSP programming. I have an issue with reading files. I am trying to call method of a normal java file from a jsp program. The method I am trying to call does some IO operation on Files. I have the files in the same directory as my class files on server that is in WEB-INF/classes folder. In my java program, I am giving just the file name to open because the files and the classes are in the same directory. But this is not working.
What exactly should I do to read a file from a java program, that is running on the server?
Any help is appreciated.
Thanks,
KrishnaString realFilePath = application.getRealPath("/WEB-INF/myFile.txt");
File fileToOpen = new File(realFilePath);
out.println(fileToOpen.getAbsolutePath() + ": exists? " + fileToOpen.exists());in this case "application" is a reference to the ServletContext.
It is an implicit variable in a JSP. In a servlet:
ServletContext application = getServletConfig().getServletContext(); -
How to run a cygwin.bat from a java program?
Can you please let me know how to run a cygwin.bat file from a java program and to give commands through java program. I have a program to run .exe files, but when I do the same for the cygwin.bat it doesnt work. In task mgr a BASH and a cmd.exe is running. Please help me on this & bit urgent. Thanks in advance!
Can you please let me know how to run a cygwin.bat
file from a java program and to give commands through
java program. I have a program to run .exe files, but
when I do the same for the cygwin.bat it doesnt work.Of course not. .bat files are no native executables. You need to open a shell first, like "cmd /c cygwin.bat ..."
& bit urgent. Thanks in advance!If I had read this earlier I wouldn't have replied. Why exactly is your time worth more than anybody else's? -
Uncompress a .tar.gz file from in java
I need to unconpress a .tar.gz file from my Java program. Does anyone have any information on how I might go about this? I was not able to use the java.util.zip package since it does not recognize the file format.
Do I have to use Runtime and run some external program. If so does anyone know of a freeware zip utility that works on the commandline and uncompresses a .tar.gz file.
Thanks,
CogTry
http://www.trustice.com/java/tar/
Holger -
Launch 2 batchs from a java program
Hi,
My pb is the following one:
I launch a batch file from my java program. This batch launch another program. But it seems that the java program take back the hand and stop the execution of the last program.
How can I make the java program waiting?
Thanks in advanceThanks Felipe.
I've tried your suggestion and I've discerned the real bug. In fact, it's the program that I launch through the batch file which don't perform.
Here is my batch file:
C:\program files\pvcs\vm\win32\bin\pcli.exe run -sC:\program files\pvcs\vm\win32\bin\noexiste.pcli %1 %2 %3
In fact, it has to launch pcli.exe, which has to launch a script.
The pb is that when I run the batch file manually, it works. So, it comes from the java prg. Here is the command lines in my program java:
try
String cmd = "C:/Progra~1/Pvcs/Vm/Win32/Bin/transfert.bat";
String[] cmdArray = { cmd, Str_LabelModule, Str_FichierSauvegarde, Str_AccesArchive };
Prc_MyProcess = Rt_MyRuntime.exec(cmd);
System.setProperty("ATTENTE", "VRAI");
while(!b_stop)
if(!System.getProperty("ATTENTE").equals("VRAI"))
b_stop = true;
else
Thread.sleep(1000);
}catch (Exception exc) {exc.printStackTrace();}
I tried this program with a simple batch (echo %1 %2 %3 > c\toto.txt) and it works.
Have you an explanation for this? -
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.
-
How to create windows executable file from a java file. Please help.
Hi,
For my project I developed the codes in Java. It is working well with java run time environment. But without that I can not run it. I need to create a exe file (windows executable file) from the java source code. If you have any idea please share it with me.
Even if you know it very lightly, please help with what you know. That would be a big help for me.
Thank you very much.Does anybody know how to read a manual?
Matt Richardson
Certified LabVIEW Developer
MSR Consulting, LLC
Maybe you are looking for
-
How to change the maximum frame rate of the camera by changing the image size?
I have two acA2040-180km cameras which are connected to 2 NI PCIe-1433 framegrabbers, I am monitoring my cameras by LabView, maximum allowable frame rate is about 187 for full resolution images, but I just need a small fraction of the images, I know
-
How to restrict the number of batch jobs used by middleware?
Hi, I'm using middleware to replicate data which send IDOCs from one system to another. I know on source system, I can use SMQS to restrict the number of connections. But on target system, can I use any tool to restrict number of batch jobs? Becau
-
Drop Down in self registration
Hi All, I am working on customization of self registration page. Everything is fine if I am using TEXT FIELDS in self registration. If use drop down and Date Fields in self registration page i am able to see the drop down and date fields in self regi
-
Need documentation on weblogic server properties
Hi, Could any one be so kind to help me knowing the weblogic server properties like weblogic.Name, weblogic.Rootdirectory etc and their documentation. Many many thanks to you. Warm Regards, Prasanna Lakshmi tallapaka
-
suppose you create an album of photos imported from your iPhone with roll, then delete those photos on the roll ... because they were also deleted on the album?