I'm trying to get the names of all the files in a folder "clock" which is inside the working directory "src".
The snippet below works fine if I run it but when I build the JAR file and run that I get a null error.
try {
File directory = new File("src/clock/");
File[] files = directory.listFiles();
for (File f: files) {
text.appendText(f.getName() + " ");
}
} catch (Exception e) {
text.appendText(e.getMessage() + " ");
}
File structure:
Update: (I'm using the ResourceAsStream now but same problem runs fine, deployed JAR doesn't work)
public void setImage() {
List<String>fn;
try {
fn = getResourceFiles("/clock/graphics/backgrounds/");
for (String s: fn) {
text.appendText(s);
}
} catch (Exception e) {
label.setText(e.getMessage());
}
}
private List<String>getResourceFiles(String path) throws IOException {
List<String> filenames = new ArrayList<>();
try (
InputStream in = getResourceAsStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader( in ))) {
String resource;
while ((resource = br.readLine()) != null) {
filenames.add(resource);
}
}
return filenames;
}
private InputStream getResourceAsStream(String resource) {
final InputStream in = getContextClassLoader().getResourceAsStream(resource);
return in == null ? getClass().getResourceAsStream(resource) : in ;
}
private ClassLoader getContextClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
That's because File searches in the
/path/to/your/application.jar
which File cant unzip to find the files in the specified path. It considers application.jar as a folder name and tries to read it.
Instead use
ClassLoader classLoader = YourClassName.class.getClassLoader();
InputStream sam = classLoader.getResourceAsStream(fileName);
to read the file from resources folder of the project when you want your jar to read a file.
Related
I want to create log file and write some text to that file in java .I completed that task.when run jar file this code working well.but after create setup.exe using exe4j file writing process not working.any one know how to do this?
this is how I get path of jar file located directory
File f = null;
public String baseUrl() {
try {
if (f == null) {
f = new File(Register.class.getProtectionDomain().getCodeSource().getLocation().toURI().getRawPath());
}
String path = f.getParent();
return path;
} catch (URISyntaxException ex) {
System.out.println(ex);
}
return "";
}
This is my log file creating process
try {
src.Log lg = new src.Log();
lg.setAction(action);
lg.setUserName(userName);
lg.setDescription(description);
lg.setTime(date);
lg.setSyncPath(syncPath);
lg.setMethod(method);
String url = baseUrl();
System.out.println(baseUrl());
String directoryName = url + "/ResFile";
File directory = new File(directoryName);
if (!directory.exists()) {
directory.mkdir();
}
File log = new File(directoryName + "/log.txt");
if (log.exists() == false) {
log.createNewFile();
}
try (PrintWriter out = new PrintWriter(new FileWriter(log, true))) {
out.append(lg.toString());
}
} catch (Exception ex) {
System.out.println(ex);
}
If you use the "JAR in EXE" mode, your log file will end up in a temporary directory, because that's where the JAR files are extracted at run time.
To get the directory where the executable is located, you can use
System.getProperty("install4j.exeDir")
I have made the code which renames all the jpg files in a directory from 1 to n (number of files)..
if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg
But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file
I have wasted one day to resove that issue
Kindly help me
Code:
public class Renaming {
private static String path; // string for storing the path
public static void main(String[] args) {
FileReader fileReader = null; // filereader for opening the file
BufferedReader bufferedReader = null; // buffered reader for buffering the data of file
try{
fileReader = new FileReader("input.txt"); // making the filereader object and paasing the file name
bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
path=bufferedReader.readLine();
fileReader.close();
bufferedReader.close();
}
catch (FileNotFoundException e) { // Exception when file is not found
e.printStackTrace();
}
catch (IOException e) { // IOException
e.printStackTrace();
}
finally {
File directory=new File(path);
File[] files= directory.listFiles(); // Storing the all the files in Array
int file_counter=1;
for(int file_no=0;file_no<files.length;file_no++){
String Extension=getFileExtension(files[file_no]); //getting the filw extension
if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){ // checking that if file is of jpg type then apply renaming // checking thaat if it is file
File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file
new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg")); //Renaming the file
System.out.println(new_file.toString());
file_counter++; // incrementing the file counter
}
}
}
}
private static String getFileExtension(File file) { //utility function for getting the file extension
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1); // gettingf the extension name after .
} catch (Exception e) {
return "";
}
}`
first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS.
This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.
public class App {
private String path = null;
public static int index = 1;
public App(String path){
if (Files.isDirectory(Paths.get( path ))) {
this.path = path;
}
}
public void rename() throws IOException{
if ( this.path != null){
Files.list(Paths.get( this.path ))
.forEach( f ->
{
String fileName = f.getFileName().toString();
String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");
try {
Files.move( f ,Paths.get( this.path + "/" + App.index + "." + extension));
App.index++;
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
}
public static void main(String[] args) throws IOException {
App app = new App("c:/Temp/");
app.rename();
}
}
I need to copy the directory "src" that is located in my java project, as a common resource. This "src" folder contains other subfolders and files, so I need them to be copied as well. How can I achieve something like this??
The main problem I'm facing is that I can't retrieve the absolute path of my "src" folder.
A solution would be to copy file by file but their are too much and I would like to find a better solution
Thank you
EDIT:
When the user click on "Generate" button, my app ask to the user a target location where to generate some files. This target location is where I want to copy my "src" folder with all its children. The "src" folder, as sad above, is located in my java project main folder.
If you want to extract the sources from a jar file you could start with this short example
public class UnZip {
public static void main(String argv[]) {
String destDir = "/tmp/";
String sourceJar = "your_src.jar";
try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceJar)))) {
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
File newDestination = new File(destDir + zipEntry.getName());
if (zipEntry.isDirectory()) {
unzipDir(newDestination);
} else {
unzipFile(newDestination, zis);
}
}
} catch (IOException ex) {
System.err.println("input file coud not be read " + ex.getMessage());
}
}
private static void unzipFile(File file, final ZipInputStream zis) {
System.out.printf("extract to: %s - ", file.getAbsoluteFile());
if (file.exists()) {
System.out.println("already exist");
return;
}
int count;
try (BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE)) {
while ((count = zis.read(BUFFER, 0, BUFFER_SIZE)) != -1) {
dest.write(BUFFER, 0, count);
}
dest.flush();
System.out.println("");
} catch (IOException ex) {
System.err.println("file could not be created " + ex.getMessage());
}
}
private static void unzipDir(File dir) {
System.out.printf("create directory: %s - ", dir);
if (dir.exists()) {
System.out.println("already exist");
} else if (dir.mkdirs()) {
System.out.println("successful");
} else {
System.out.println("failed");
}
}
static final int BUFFER_SIZE = 2048;
static byte[] BUFFER = new byte[BUFFER_SIZE];
}
I resolved the problem creating a zip archive of the app I need to generate. Then from my project I unzip this archive taken from resource folder and after that I open the stream of the java file I need to modify and I edit it.
This is the code, similar to SubOptimal's solution
UnzipUtility unzipper = new UnzipUtility();
InputStream inputStream = getClass()
.getResource("/template/template.zip").openConnection()
.getInputStream();
unzipper.unzip(inputStream, parentFolder.getCanonicalPath());
The UnzipUtility class is from this example: http://www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java
I have a Java Class UpdateStats in WEB-INF/Classes directory of a dynamic web application.This class has a function writeLog() which writes some logs to a text file.I want this text file to be in webcontent directory.Thus everytime the function is called updates stats are written in that text file.
The problem is how to give the path of that text file in webcontent directory from within that function,which resides in WEB-INF/Classes directory.
You can get your webapp root directory from ServletContext:
String path = getServletContext().getRealPath("WEB-INF/../");
File file = new File(path);
String fullPathToYourWebappRoot = file.getCanonicalPath();
Hope this helps.
You can do something like below in your servlet,
When you do getServletContext().getRealPath() and put some string argument the file will see at your webcontent location.
If you want something into WEB-INF, you can give fileName like "WEB-INF/my_updates.txt".
File update_log = null;
final String fileName = "my_updates.txt";
#Override
public void init() throws ServletException {
super.init();
String file_path = getServletContext().getRealPath(fileName);
update_log = new File(file_path);
if (!update_log.exists()) {
try {
update_log.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error while creating file : " + fileName);
}
}
}
public synchronized void update_to_file(String userName,String query) {
if (update_log != null && update_log.exists()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(update_log, true);
fos.write((getCurrentFormattedTime()+" "+userName+" "+query+"\n").getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
To write a file you need to know absolute path of your web content directory on server as file class require absolute path.
File f = new File("/usr/local/tomcat/webapps/abc/yourlogfile.txt");
FileOutputStream out = new FileOutputStream(f);
out.writeLog("Data");
Assumption : abc is your project name
WebContent is not any directory when you deploy application. All files under web content goes directly under project name.
Currently, I can only make my app access to the XML database when the jar file and XML file in the same directory, and what I hope is that there is only one single jar file which includes the XML file. How can I do that?
private String getXmlPath() {
String url = "";
try {
String cp = "Data\\QuestionList.xml";
File f = new File(ClassLoader.getSystemResource("\\").toURI().getPath());
url += f.getPath() + "\\" + cp;
} catch (URISyntaxException ex) {
url="QuestionList.xml";
}
System.out.println(url);
return url;
}
public void classifyQuestionnaire(String path)
throws FileNotFoundException, XMLStreamException, JAXBException {
// Parse the data, filtering out the start elements
XMLInputFactory xmlif = XMLInputFactory.newInstance();
FileReader fr = null;
if (path == null) {
fr = new FileReader(getXmlPath());
} else {
fr = new FileReader(path);
}
XMLEventReader xmler = xmlif.createXMLEventReader(fr);
EventFilter filter = new EventFilter() {
#Override
public boolean accept(XMLEvent event) {
return event.isStartElement();
}
};
You can include xml file into the jar. These non-class files are usually called "resource". It depends on how you're creating the jar, but it's usually straight forward. See Java: Load a resource contained in a jar for reading the resource.