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")
Related
In my android application i'm using SQLite database.
And I need to have an option in the app to download the database file.
Because sometimes I need to view the data there , so the user will download the file and send it to me and i will browse it using SQLite browsers.
Is the doable? if yes how?
String src = "/data/data/myPackage/databases/Mydb.db";
String dest = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
copyFileOrDirectory(src , dest);
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
copyFile(src, dst);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
Usually, the SQLite database is available in the /data/data/your.applications.package/databases/database.db path.
So, you could use that path; however, I suggest that you get the Database Path in the following way:
File dbFile = getDatabasePath("dbname");
String dbPath = dbFile.getPath();
Then, you can copy the database from this folder into the folder that you desire.
Copying the database to the Downloads could simulate the "download" of the SQLite database.
I've a Java program that is copying a file from Unix to hdfs. It is running fine however I am looking for impersonating a different account when it runs and copies file.
Input: Apart form input file and target hdfs directory path, another input should be properties file containing account, keytab directory, domain
Please kindly let me know the best way to move forward.
I am currently exploring using a shell to first issue a kinit command and then run the jar
I am also reading about Jaas and how this can be done in Java itself - from - https://henning.kropponline.de/2016/02/14/a-secure-hdfs-client-example/
Need inputs and any reference of available options.
My Java program that copies file is as below:
public class FileCopy implements Runnable {
#Option(names = {"-i","--input"}, required=true, description="file name to copy to hadoop")
String input;
#Option(names = {"-o","--output"}, required=true, description="hdfs directory path to be copied into")
String output;
public void run() {
Properties hadoop_properties = new Properties();
HdfsFileDeploy hdfsFileDeploy = new HdfsFileDeploy();
try {
hadoop_properties.load(FileCopy.class.getClassLoader().getResourceAsStream("hadoop.properties"));
} catch (IOException e) {
e.printStackTrace();
}
FileSystem fs = hdfsFileDeploy.configureFilesystem(hadoop_properties.getProperty("coreSitePath"),hadoop_properties.getProperty("hdfsSitePath"));
String status = hdfsFileDeploy.writeToHDFS(fs,input,output);
if (status == "SUCCESS") {
System.out.println("completed copying");
} else {
System.out.println("copying error");
}
hdfsFileDeploy.closeFileSystem(fs);
}
public static void main(String[] args) throws IOException {
CommandLine.run(new FileCopy(), args);
}
}
public class HdfsFileDeploy {
public FileSystem configureFilesystem(String coreSitePath, String hdfsSitePath) {
FileSystem fileSystem = null;
try {
Configuration conf = new Configuration();
Path hdfsCoreSitePath = new Path(coreSitePath);
Path hdfsHDFSSitePath = new Path(hdfsSitePath);
conf.addResource(hdfsCoreSitePath);
conf.addResource(hdfsHDFSSitePath);
fileSystem = FileSystem.get(conf);
System.out.println(fileSystem);
return fileSystem;
} catch (Exception ex) {
ex.printStackTrace();
return fileSystem;
}
}
public void closeFileSystem(FileSystem fileSystem) {
try {
fileSystem.close();
} catch (Exception ex) {
System.out.println("Unable to close Hadoop filesystem : " + ex);
}
}
//
public String writeToHDFS(FileSystem fileSystem, String sourcePath, String destinationPath) {
String failure = "FAILURE";
String success = "SUCCESS";
Boolean doNotDelSrc = false;
Boolean overwrite = true;
try {
Path inputPath = new Path(sourcePath);
Path outputPath = new Path(destinationPath);
if(!fileSystem.exists(outputPath)) {
System.out.println("Output path " + outputPath + " does not exist. Creating outputPath directory now..");
if (fileSystem.mkdirs(outputPath)) {
System.out.println("Output path " + outputPath + " created...");
}
}
System.out.println("about to copy from " + inputPath + " to " + outputPath);
fileSystem.copyFromLocalFile(doNotDelSrc, overwrite, inputPath, outputPath);
return success;
} catch (IOException ex) {
System.out.println("Some exception occurred while writing file to hdfs");
ex.printStackTrace();
return failure;
}
}
}
Input1: input file
Input2: target hdfs directory
Reference Input: file (say yaml) containing account, domain, keytab path.
jar should impersonate and copy the input file to target hdfs directory.
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.
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.