Renaming files in a java program
Hi,
I want to give users the option of renaming a file from within a java GUI. They will right click on the name of the file in a JList, a JPopup will appear and they will click on rename and type a new name for the file(i've already done upto this point). How do I actually change the name of the file on my hard drive.
I would also like to be able to delete files from the program.
Thanks
Jim
Jim,
You may use the java.io.File class to achieve these. Assume you want to rename the file /tmp/myTemp/toto.tmp into /home/me/useless.old
Simply do the following things:
File f = new File("/tmp/myTemp/toto.tmp");
f.renameTo("home/me/useless.old");
To delete a file, there is a delete() or destroy() method. Check the API for more details (java.io package). Anyway you should already use this class for the purpose of your soft!
Hope it helps,
Stephane
Similar Messages
-
How to read an XML file into a java program?
hi,
i want to load the following very simple xml file in my java program.
<root>
<weblogic>
<url value="t3://192.168.1.160:7001" />
<context value="weblogic.jndi.WLInitialContextFactory" />
</weblogic>
</root>
I am getting the error: " Line=1: cvc-elt.1: Cannot find the declaration of element 'root'."
What might be the problem can anyone help me out.
My java class code is:
public class BIXMLReader {
/** All output will use this encoding */
static final String outputEncoding = "UTF-8";
// Parses an XML file and returns a DOM document.
// If validating is true, the contents is validated against the DTD
// specified in the file.
public static Document parseXmlFile(String filename, boolean validating) {
try {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setIgnoringComments(false);
factory.setIgnoringElementContentWhitespace(false);
factory.setCoalescing(false);
factory.setValidating(validating);
// Create the builder and parse the file
System.out.println("filename = " + filename);
DocumentBuilder db = factory.newDocumentBuilder();
// Set an ErrorHandler before parsing
OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, outputEncoding);
db.setErrorHandler(new MyErrorHandler(new PrintWriter(errorWriter, true)));
Document doc = db.parse(new File(filename));
System.out.println(doc.toString());
return doc;
} catch (SAXException e) {
System.out.println("A parsing error occurred; the xml input is not valid. " + e.getMessage());
} catch (ParserConfigurationException e) {
System.out.println("Parser configuration exception has occured");
} catch (IOException e) {
System.out.println("IO Exception has occured " + e.getMessage());
return null;
// Error handler to report errors and warnings
private static class MyErrorHandler implements ErrorHandler {
/** Error handler output goes here */
private PrintWriter out;
MyErrorHandler(PrintWriter out) {
this.out = out;
* Returns a string describing parse exception details
private String getParseExceptionInfo(SAXParseException spe) {
String systemId = spe.getSystemId();
if (systemId == null) {
systemId = "null";
String info = "URI=" + systemId +
" Line=" + spe.getLineNumber() +
": " + spe.getMessage();
return info;
// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.
public void warning(SAXParseException spe) throws SAXException {
out.println("Warning: " + getParseExceptionInfo(spe));
public void error(SAXParseException spe) throws SAXException {
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
public void fatalError(SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}ok thanks, i can get the elements, but why did it not validate it?
I want to read the child nodes of "weblogic" not by their name but by their index. Because i dont want to confine the reader so i want to read all the child nodes of weblogic (looping over them). i m doing the following but its not returning me the correct result and giving me the wrong count of child nodes.
Element elementNode = (Element)doc.getElementsByTagName("weblogic").item(0);
NodeList nodeList = elementNode.getChildNodes();
int length = nodeList.getLength();
System.out.println("length = "+ length); // the length its giving is 5 but i shuld get only 2
for(int i=0; i < length; i++) {
Element elmChild = (Element) nodeList.item(i);
System.out.println(elmChild.getAttribute("value"));
what might be the problem? -
How to run an exe file in a java program
Hi,
Can somebody tell me how to run an exe file in a java program.
Thank you!Yes, java.lang.Runtime.exec().
Read this carefully before you do:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
Don't write a line of code before you're reviewed and understood the article completely. - MOD -
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 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 -
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!
JoeYou 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
... -
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 -
Windows task scheduler to run batch file running a java program
I have created a batch file that runs my SendEmail program. The batch file is in the same directory as the java program. The only line in the batch file is
java SendEmail
This works fine from the command prompt but from the windows task scheduler it fails to function. Any help on how I can overcome this problem will be greatly appreciated.
THanksLooks okay. The classpath is set, too, I guess? Btw, try running javaw instead of java. I may err, but I think it can show a console, so you can watch any error messages.
-
Compiling one java file within another java program
Hi all,
I want to compile one java file say one.java within a java program say second.java.. i simply have no idea as how to proceed ..pls help!!http://onesearch.sun.com/search/onesearch/index.jsp?qt=dynamically+compile&subCat=siteforumid%3Ajava31&site=dev&dftab=siteforumid%3Ajava31&chooseCat=javaall&col=developer-forums
Just to give you an idea. -
How to call windows help files .hlp from Java program
Hai all everybody
How to call windows Help file that is xxx.hlp files from java programs
any help great!!!!
regards
veeruHow about
Runtime.getRuntime().exec("start xxx.hlp"); -
Making batch files to execute java programs in windows
In my comp sci class, i found a folder with a batch file, an application file, and all class files necessary to run the program.
how do i take my java program and make a batch file to run it (in dos) like that program in my comp sci class?Okay, here are your steps for running a java program from a batch file:
1) Open Notepad
2) type the following:
set JAVA_HOME=C:\j2sdk1.4.0_03 // specify the path where your jdk is
set path=%JAVA_HOME%\bin;.
javac {-classpath .;one.jar;two.jar} YourProgramName.java
java {-classpath .;one.jar;two.jar} YourProgramName
The stuffs inside {} is not necessary if your program doesnt use any .jar files.
3) Save the notepad as mybatch.bat in the directory where your Java program is located.
4) In the DOS prompt, go to the directory where you have .java and .bat files
(use 'cd' command)
5) Now, type mybatch.bat and press ENTER.
Thatz it. Your program runs like a charm now!!!
(provided the compiler is pleased with ur code :)
-- layman's pal -
Batch File to run Java Program
I'm trying to create a batch file that will run a java program without opening it up, compiling, and executing:
JAVA.EXE "C:\(path).class"
It keeps giving me the error message:
Exception in thread "main" java.lang.NoClassDefFoundError: C:\\(path)/classallright... i switched up the batch file to the format
you gave me. It seems better, but now it has a problem
with TerminalIO.KeyboardReader. The error message was:
Exception in thread "main"
java.lang.NoClassDefFoundError:
TerminalIO/KeyboardReader
at util.<clinit>(util.java:18)
at GPA_Calculator.<clinit>(GPA_Calculator.java:3)
util line 18 is:
private static KeyboardReader input = new
KeyboardReader ();Sounds like you've got alot of non-standard classes there ... I could not begin to speculate. Is this something you wrote or inherited? If it is not too large you could try posting the code ... but it sounds like that would not be practicle. At any rate I can't see how it's working better if it is still not working :S -
Running Batch file thru a java program
hai friends
i have a batch file like hello.bat
how can i run that batch file when i run my java program
i heard that Runtime.exec() is used to run the batch files.
can i use Runtime.exec() to run my hello.bat file or any other things i need to use ?
Thankyou VeryMuch
Yours
RajeshYes, you can use Runtime. You should look it up in your API guide, but this code might get your started:
try
Process p = runtime.exec("command.com /c c:\\hello.bat");
catch(IOException e)
System.out.println("Failed");
}Your API guide will explain how to get a Runtime object. The syntax is very straightforward. -
How to compile a java file in a java program
Hi,
I don't know to compile a java file in a java class.
Could somebody help me?
Thanks.if ur using windows...
goto ur directory and then type
javac FILENAME.java
and ur done!
Maybe you are looking for
-
Can I have the same library on two different computers
I have my iTunes library on a external drive linked to my work computer. Can I link it to my home computer too?
-
I can no longer have more than three web pages open at one time.
I used to be able to have many web pages open at once and go back and forth between them as I pleased. Now--only three. I have no idea why.
-
MSI 915GM-FR Socket T (LGA 775) Intel 915G Micro ATX Intel Motherboard
Yes, because of recent turbulence considering some of the ram I recently bought, I am looking for different Ram that is compatible with this board: MSI 915GM-FR Socket T (LGA 775) Intel 915G Micro ATX Intel Motherboard I know that some places
-
Internet connection not working after computer wakes up from sleep. OSX Lion
After upgrading to Lion, I noticed that my internet connection doesn't work when I wake my computer from sleep. I have to turn off the WiFi connection, turn it back on and it will work. I guess this is a glitch that will be fixed later on. Just wante
-
Can't hear myself record with Apogee Duet in Logic
i have input monitoring on but don't hear anything through my mic. I'm getting signal but i can't hear myself through the headphones. am i missing something?