File handling in core java - java

I need to do some housekeeping.I accidentally setup my classpath same as my codebase and all classes are placed along with my code.I need to write a quick java program to select all files of the type .class and .class alone and delete it immediately.Has anyone done something related to this?

Why don't you use the shell to do that, something like:
Linux:
find . -name *.class -print -exec rm {} \;
Windows:
for /r %f in (*.class) do del %f

find . -name "*.class" -exec rm '{}' \;

This might work. Untested. Those find/for commands by the others look promising, too, but just in case you are on an OS/390 mainframe here is the Java. ;-)
import java.io.File;
import java.io.IOException;
public class RemoveClass {
public static void main(String[] args) throws Exception {
File f = new File(".");
deleteRecursive(f);
}
public static void deleteRecursive(File f) throws IOException {
if (f.isDirectory()) {
for (File file : f.listFiles()) {
deleteRecursive(file);
}
} else if (f.isFile() && f.getName().endsWith(".class")) {
String path = f.getCanonicalPath();
// f.delete();
System.out.println("Uncomment line above to delete: [" + path + "]");
}
}
}

Related

Can't use java.io.* on CodeRunner

import java.io.*;
public class WriteFile {
public static void main(String[] args){
try {
FileWriter writer = new FileWriter("Test.txt");
writer.write("this is a plain text file.\n");
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
错误: 找不到或无法加载主类 O:WriteFile
原因: java.lang.ClassNotFoundException: O:WriteFile
This code can run on both eclipse and vs Code but not on Coderunner. How to solve it.
Your classpath is broken.
Method #1
Try adding the classpath while running it.
On windows:
java -classpath .;yourjar.jar YourMainFile
On Unix:
java -classpath .:yourjar.jar YourMainFile
Method#2
Configure the build path in your IDE and add an external JAR containing your class to the build path.
Method#3
Please read this to resolve the issue.
Note:
You could also refer to this.

Adding a External Folder to the ClassPath in a runnable jar

I have a maven project where I create a jar with dependencies using maven assembly plugin. I also have an external config file ( conf.properties ) that is required by the jar to work properly.
My project structure is like this:
|- abc.jar
|- config
|-conf.properties
How can I add this config folder to the classpath of the jar file? I tried to do this using -cp command and manipulating class-path property in MANIFEST.MF file but no luck so far.
Does anyone know a way to do this?
This is how I tested (sorry, no maven)!
Main class:
package cfh.sf.Chamika;
import java.util.ResourceBundle;
public class ABC {
public static void main(String[] args) {
var bundle = ResourceBundle.getBundle("conf");
System.out.println(bundle.getString("test"));
}
}
Manifest file, note empty line at end (entries must end with a newline (CR, LF or CRLF)):
Manifest-Version: 1.0
Main-Class: cfh.sf.Chamika.ABC
Class-Path: config/
Directory structure
dist/
abc.jar
config/
conf.properties
Content of conf.properties:
test = OK, it is working!
Executed with
java -jar abc.jar
Alternative, not using ResourceBundle:
package cfh.sf.Chamika;
import java.io.IOException;
public class ABC {
public static void main(String[] args) {
try (var input = ClassLoader.getSystemResourceAsStream("conf.properties")) {
int ch;
while ((ch = input.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

How to get path to class file in eclipse and linux in java?

In eclipse for windows, when I run
public class HelloWorld {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
}
}
It gives me the path of the project root folder (which contains the bin folder which has the class file). For example
SampleProject
and the class file is actually located at
SampleProject\bin\myclass.class
But if I run the same program in linux with
javac myclass.java
java myclass
it gives me the directory that has the .class file, which is the same as pwd command. This is what I want in eclipse for windows. I want some code that will give me the path to the class file in both eclipse for windows and linux.
Does anyone know how do this?
Thanks
If I understand you correctly, you'd like a method that retrieves a class' path on disk. This is easily achievable, like so:
public String getClassPath(Class c) {
try {
return c.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
NOTE this will work even if the class is contained in a jar file. It will return the path to the jar in this case.
The easiest way is to do this:
public class HelloWorld {
public static void main(String[] args) {
System.out.println(HelloWorld.class.getResource("HelloWorld.class"));
}
}

Run Non GUI Jar Files

I know that I can run non GUI jar files from the command line. Is there any way that can do so by clicking or something and not writing the commands again and again.? Is there any software to do so. ( I am talking about a compiled jar and don't want to run from any ide)
public static final String TITLE = "CONSOLE title";
public static final String FILENAME = "myjar.jar";
public static void main(String[] args) throws InterruptedException, IOException {
if(args.length==0 || !args[args.length-1].equals("terminal")) {
String[] command;
if(System.getProperty("os.name").toLowerCase().contains("win")) {
command = new String[]{"cmd", "/c", "start \"title \\\""+TITLE+"\\\" & java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
} else {
command =new String[]{"sh", "-c", "gnome-terminal -t \""+TITLE+"\" -x sh -c \"java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
}
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
} catch(Throwable t){
t.printStackTrace();
}
} else {
//THERE IS YOUR CONSOLE PROGRAM:
System.out.println("Hey! What's your name?");
String read = new BufferedReader(new InputStreamReader(System.in)).readLine();
System.out.println("Hey, "+read+"!");
Thread.sleep(10000);
}
}
You can run it with double clicking on .jar file. Don't forget about MANIFEST.MF! :) (working on linux, also!)
Example (I only double clicked on jar file):
The way intended by Java is that you call java -jar XXXX.jar on the jars you need. Drawback is that you can't specify a classpath so all classes should be there.
A cooler way to package an application is by using Java WebStart. With that the user installs the application jut by clicking on a web browser. Check here http://docs.oracle.com/javase/8/docs/technotes/guides/javaws/developersguide/contents.html

Running java program from another java program

I'm trying to run a Java program from another Java application. Here is my code:
public class Main {
public static int Exec() throws IOException {
Process p = Runtime.getRuntime().exec("javac -d C:/Users/Dinara/Desktop/D/bin "
+ "C:/Users/Dinara/Desktop/D/src/test.java");
Process p1 = Runtime.getRuntime().exec("java -classpath C:/Users/Dinara/Desktop/D/bin test");
return 0;
}
public static void main(String[] args) throws IOException {
Exec();
}
}
javac works fine and creates test.class file in bin directory. However java -classpath C:/Users/Dinara/Desktop/D/bin test does not run the test.class file.
the content of the test.java:
import java.io.*;
class test {
public static void main(String args[]) {
try {
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
I suppose that something wrong with recognizing Java command. Could you please give me a sample code for fixing this problem or share idea? I'm using Netbeans to run Main class and the location of the application folder is C:\Users\Dinara\Main
Use
System.getProperty("java.home") + "/bin/java -classpath C:/Users/Dinara/Desktop/D/bin test"
instead of
"java -classpath C:/Users/Dinara/Desktop/D/bin test"
You need to supply the full path to the javac, exec won't use the ath to find it for you

Categories

Resources