How to change permissions to incoming file in linux using JAVA - java

Objective
I want that whenever someone uploads a file (name is Accounts 0998.csv) in /opt/file/incoming directory. Its permissions gets change to chmod 664 i.e rw-rw-r
I am using linux.
I want to automate this process so I am writing a java program but its working
package com.reader.file;
import java.io.File;
import java.io.IOException;
public class GrantPermission
{
public static void main( String[] args )
{
try {
File file = new File("/opt/file/Accounts 0998.csv");
if(file.exists()){
System.out.println("File exists.");
//using PosixFilePermission to set file permissions 664
Set<PosixFilePermission> perms = new
HashSet<PosixFilePermission>();
//add owners permission
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
//add group permissions
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
//add others permissions
perms.add(PosixFilePermission.OTHERS_READ);
Files.setPosixFilePermissions(file.toPath(), perms);
} catch (IOException e) {
e.printStackTrace();
}
}
else{
System.out.println("File does not exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Additional Information
I am using WSO2 ESB it first search for a file then If file exists then I want to change its permission (via using Class mediator i.e JAVA) and then move it to another directory but my GOAL is change file permissions to rw-rw-r

You can use NIO.2 if you are using java7 or later.
See:
How do i programmatically change file permissions?
//if you need rw-rw-r permissions
public void setPermission(File file) throws IOException{
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.OTHERS_WRITE);
perms.add(PosixFilePermission.GROUP_READ);
Files.setPosixFilePermissions(file.toPath(), perms);
}

Related

File not being renamed in Android 10

I wrote a solution for renaming files, but nothing happens in Android 10, although in 11 and above it is renamed normally.
public class PathDiv {
public static String dev(String path){
return path.replaceAll("^(.*)/.*?$","$1");
}
public static void renameFilesInDir(String path, String dirIn, String ext) {
File checkFile = new File(path);
if (checkFile.isFile()) {
try {
checkFile.renameTo(new File(dirIn, ext));
} catch (Exception e) {
e.printStackTrace();
}
}
}
path: /storage/emulated/0/Music/04. Kasger - Highland.mp3 dirIn: /storage/emulated/0/Music ext: Highland.mp3
PathDiv.renameFilesInDir(songItem.realUri,PathDiv.dev(songItem.realUri),newName.toString())
What's the problem?
In Android 10 and Higher Version of android, you can't Rename or Delete directly.
For Rename or Delete a media file you want to send a request.
Here Read Android Official Document how to create a request
For your information, to Delete a media file Dependency Available here you can use it easily it's created by me
checkFile.renameTo(new File(dirIn, ext)); It Also Works for this you want to add ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION permission in your app but before using this permission please refer to Google Play Police Update

can I get the directory of another file?

I have created an auto-updater for my java program. but at the end of the download it downloads the file to desktop. I can to get where is the program file and update it?
this is my code:
#Override
public void run() {
if(!Debug) {
try {
FileUtils.copyURLToFile(new URL("fileurl"), new File(System.getenv("APPDATA") + "\\file.zip"));
UnzipUtility unzip = new UnzipUtility();
File deskfile = new File(System.getProperty("user.home") + "/Desktop/file.jar");
if(deskfile.exists()) {
deskfile.delete();
}
unzip.unzip(System.getenv("APPDATA") + "\\file.zip", System.getProperty("user.home") + "/Desktop");
File file = new File(System.getenv("APPDATA") + "\\file.zip");
file.delete();
Successfull = true;
} catch (IOException e) {
Successfull = false;
}
try {
Updater.sleep(0L);
}catch(Exception e) {
e.printStackTrace();
}
}
}
this is the code present in my external updater jar and I need to find the main program directory what can I do?
For example, if the main program is in any other directory except the Desktop, the update will always download it to the desktop ... I need it to change the file that executes the command to start the updater
If your external updater is in the same directory as your mail application you can use:
System.getProperty("user.dir");
This will give you the current folder. You can find more details here: https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
If this is not the case i see the following options:
ask the user before updating for the installation folder
store the installation folder in property file inOS user data // update jar folder.
regards, WiPu

Not able to open application package directory of my Android application

I am trying to write a text file to internal storage of my android application. But it is not possible for me to see if the file is generated or not.
My text file is stored in the following path:
data/data/"MyApplcationPackageName"/files/MyFile.txt
Permission : drwxrwx-x
I have tried the following things -
1) Using device file explorer:
Device file explorer does not open my application package. it gives following error if I try to open it.
Device File Explorer
2) Terminal:
I have also tried opening it using adb in the terminal. But when I try to open files inside my application package it says permission denied.
adb terminal
Please let me know how I can open my text file for debugging. Thanks in advance.
public static void StoreDB() {
if(isExternalStorageWritable() && checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
File file = getFinalDir();
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write("something".getBytes());
fos.close();
ToastUtil.showToast(Resource.getAppContext(),"File Saved");
} catch (IOException e) {
Log.e("StoreDB", "Exception");
e.printStackTrace();
}
}
}
public static boolean isExternalStorageWritable() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Log.d("External storage", "Writable");
return true;
}
Log.d("External storage", "Not Writable");
return false;
}
public static boolean checkPermission(String Permission){
int check = ContextCompat.checkSelfPermission(Resource.getAppContext(),Permission);
boolean Perm = (check == PackageManager.PERMISSION_GRANTED);
Log.d("Check Permission", "Result: " + Perm);
return Perm;
}
private static File getFinalDir() {
return createDirIfNotExist(Environment.getExternalStorageDirectory().getPath() + "/Co_Ordinate.txt/");
}
public static File createDirIfNotExist(String path) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
Now I am trying to put the file in external storage. Above code always gives IO exception.
You need to root your phone to view those files. Or you can do it on an emulator by using the Device File Explorer.
EDIT: Or just use an unprotected file path. This will create the directory. After that you just need to save the .txt file to that directory.
private static File getFinalDir() {
return createDirIfNotExist(Environment.getExternalStorageDirectory().getPath() + "/MyAppName/");
}
public static File createDirIfNotExist(String path) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
You can do this with Emulator. Run your app in emulator and go to Android Device monitor
Choose device, go to File Explorer menu and search your text file in data folder

Get the path of a file via file explorer

First of all I'm sorry if this question has been asked before or if there is documentation about the topic but i didn't found anything.
I want to make a windows app that open windows file explorer and you can browse for and then select a mp3 file, so you can play it (and replay it) in this program. I know how to open file explorer, this is my code :
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException {
Desktop desktop = Desktop.getDesktop();
File dirToOpen = null;
try {
dirToOpen = new File("c:\\");
desktop.open(dirToOpen);
} catch (IllegalArgumentException iae) {
System.out.println("File Not Found");
}
}
}
But i don't know how to select an mp3 file and then get the path of the file, so i can play it later.
I don't think you are approaching this right. You should use something like a FileDialog to choose a file:
FileDialog fd = new FileDialog(new JFrame());
fd.setVisible(true);
File[] f = fd.getFiles();
if(f.length > 0){
System.out.println(fd.getFiles()[0].getAbsolutePath());
}
Since you are only getting 1 MP3 file, you only need the first index of the File array returned from the getFiles() method. Since it is a modal dialog, the rest of your application will wait until after you choose a file. If you want to get multiple files at once, just loop through this aforementioned Files array.
See the documentation here: https://docs.oracle.com/javase/7/docs/api/java/awt/FileDialog.html

How do I automatically convert all javadoc package.html files into package-info.java files?

We use a lot of legacy package.html files in our project and we want to convert them to package-info.java files. Doing that manually isn't an option (way too many files). Is there a good way to automate that?
We want to convert them for a couple of reasons:
From the javadoc specs: This file is new in JDK 5.0, and is preferred over package.html.
To not mix both types of files in the same codebase
To avoid that Intellij/Eclipse builds put those *.html files in our classes dirs (and possibly in a release binary jars) so they behave like our other normal html resources.
You may need to change the directory separator if you're not running windows. Also, the conversion is a bit of a hack, but it should work. Out of curiosity, how many packages do you have that manual isn't an option?
public class Converter {
public static void main(String[] args) {
File rootDir = new File(".");
renamePackageToPackageInfo(rootDir);
}
private static void renamePackageToPackageInfo(File dir) {
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return "package.html".equals(name);
}
});
for (File file : files) {
convertFile(file);
}
// now recursively rename all the child directories.
File[] dirs = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File subdir : dirs) {
renamePackageToPackageInfo(subdir);
}
}
private static void convertFile(File html) {
// determine the FQN package name
String fqpn = getPackageName(html);
// check if package-info.java already exists
File packageInfo = new File(html.getParent(), "package-info.java");
if (packageInfo.exists()) {
System.out.println("package-info.java already exists for package: "+fqpn);
return;
}
// create the i/o streams, and start pumping the data
try {
PrintWriter out = new PrintWriter(packageInfo);
BufferedReader in = new BufferedReader(new FileReader(html));
out.println("/**");
// skip over the headers
while (true) {
String line = in.readLine();
if (line.equalsIgnoreCase("<BODY>"))
break;
}
// now pump the file into the package-info.java file
while (true) {
String line = in.readLine();
if (line.equalsIgnoreCase("</BODY>"))
break;
out.println(" * " + line);
}
out.println("*/");
out.println("package "+fqpn+";");
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// queue the package.html file for deletion
//html.deleteOnExit();
}
private static String getPackageName(File file) {
StringBuilder path = new StringBuilder(file.getParent());
// trim the first two characters (./ or .\)
path.delete(0, 2);
// then convert all separators into . (HACK: should use directory separator property)
return path.toString().replaceAll("\\\\", ".");
}
}
The IntelliJ guys have made an intention to do this for all files. It's been resolved and will probably be released in the next IntelliJ release.
To do this in batch mode in IDEA:
In settings, activate the inspection gadget "'package.html' may be converted to 'package-info.java' inspection"
Open a package.html file
You see a banner fix the inspection on top the file
Click on the settings icon at the right on the banner
Select "Run inspection on" >> "Whole project"
Click on "Convert to package-info.java" >> OK
Optionally remove the inappropriate lines (sed -i "/Put #see and #since/d" `find . -name "package-info.java"`)

Categories