How to create a file using java in a webapp? - java

I am trying to make a webapps which creates a file in a specific folder. This app should work both on windows and ubuntu but they have different file structures. So how do I mention path in creation of file and again in Ubuntu I also need to use permissions. How can I give permissions to the folder in which I am trying to create a file. I am using java for this and this is my code:
//bfr=new BufferedReader(new InputStreamReader(System.in));
String fileName="/home/hemant/"+credentials[3];
String content=String.valueOf(n)+"\n"+messages.length;
File file=new File(fileName);
if(!file.exists()){
System.out.println("filecreated");
file.createNewFile();
}
my app is a tomcat based app. What should I do? I am new to this and don't have any idea.

You can get the information of Operating System using this code :
public class OSValidator {
private static String OS = System.getProperty("os.name").toLowerCase();
public static void main(String[] args) {
System.out.println(OS);
if (isWindows()) {
System.out.println("This is Windows");
} else if (isMac()) {
System.out.println("This is Mac");
} else if (isUnix()) {
System.out.println("This is Unix or Linux");
} else if (isSolaris()) {
System.out.println("This is Solaris");
} else {
System.out.println("Your OS is not support!!");
}
}
public static boolean isWindows() {
return (OS.indexOf("win") >= 0);
}
public static boolean isMac() {
return (OS.indexOf("mac") >= 0);
}
public static boolean isUnix() {
return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );
}
public static boolean isSolaris() {
return (OS.indexOf("sunos") >= 0);
}
}

If you are using servlet,you can find path using this -
String path = servletConfig.getServletContext().getRealPath("/WEB-INF")
It will work on Ubantu and WIndows.

You can check operating system, on which your webapp is deployed by:
System.getProperty("os.name");
You can create file accordingly , For giving permissions to file , full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2)
Or you can checkout this link for more information : http://www.mkyong.com/java/how-to-set-the-file-permission-in-java/

Related

How to install .xapk file from local storage programmatically in Flutter?

I want to implement this functionality;
A Button when pressed will install .xapk file from local storage with the following path.
String _apkFilePath = '/storage/emulated/0/Download/filename.xapk';
Duplicate of: I am making an .XAPK installer application in flutter. with open_file package I can open normal .apk installation dialogue but how can I install .XAPK
If you're still trying to install an .xapk file, I'm sharing a piece of code that helped me. I'm using the packages:
archive (for all the extraction as zip logic)
device_apps (to open the Settings app in case you don't have the required permissions)
open_filex (to open the apk file with the Android intent)
package_archive_info (to get the information from the .apk package)
path_provider (to get Directories and paths)
permission_handler (to ask for permissions to install)
and file_picker since I initiate the method with a picked file using that package.
abstract class XapkInstaller {
static install({required PlatformFile file}) async {
late List<FileSystemEntity> allFiles, apkFiles;
late PackageArchiveInfo appInfo;
late String appPackageName;
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
String appName = file.path.toString().split("/").last.replaceAll(".apklis", "");
String zipFilePath = "${tempDir.path.replaceAll('/$appName.apklis', '')}/$appName.zip";
// this function convert xapk in zip file and moves in appname_zip directory
_moveFile(File(file.path.toString()), zipFilePath);
final bytes = File(zipFilePath).readAsBytesSync();
final archive = ZipDecoder().decodeBytes(bytes);
// Extract the contents of the Zip archive to disk app cache.
for (final file in archive) {
final String filename = file.name;
if (file.isFile) {
final data = file.content as List<int>;
File("${tempDir.path}/$appName/$filename")
..createSync(recursive: true)
..writeAsBytesSync(data);
} else {
Directory(tempPath).create(recursive: true);
}
}
final Directory myDir = Directory("${tempDir.path}/$appName");
allFiles = myDir.listSync(recursive: true, followLinks: true);
apkFiles = allFiles.where((element) => element.path.endsWith('.apk')).toList();
for (int x = 0; x < apkFiles.length; x++) {
final String filePath = apkFiles[x].path;
try {
appInfo = await PackageArchiveInfo.fromPath(filePath);
appPackageName = appInfo.packageName;
} catch (e) {
appInfo = PackageArchiveInfo(appName: "", packageName: "", version: "", buildNumber: "");
}
if (appInfo.appName.isNotEmpty) {
try {
// moving obb file to android/obb folder
_moveObbToAndroidDir(allFiles, appPackageName);
// showing popup to install app
if (await Permission.requestInstallPackages.request().isGranted) {
await OpenFilex.open(filePath);
} else {
DeviceApps.openAppSettings(appInfo.packageName);
}
} catch (e) {
//catch error in installing
}
}
}
// clearing cache file after installing xapk
Future.delayed(const Duration(seconds: 180), () {
tempDir.deleteSync(recursive: true);
tempDir.create();
});
}
static _moveObbToAndroidDir(List<FileSystemEntity> allFiles, String appPackageName) async {
for (int x = 0; x < allFiles.length; x++) {
final fileExtension = allFiles[x].path.split("/").last.split(".").last;
if (fileExtension == "obb") {
String filepath = allFiles[x].path;
String obbFileName = filepath.split("/").last.split(".").first;
String obbDirPath = "/Android/obb/$appPackageName";
// creating the directory inside android/obb folder to place obb files
if (!Directory(obbDirPath).existsSync()) {
Directory(obbDirPath).createSync();
}
// rename path should also contains filename i.e. whole path with filename and extension
final String renamePath = "$obbDirPath/$obbFileName.obb";
try {
// syncronus copying
File(filepath).copySync(renamePath);
} on FileSystemException {
// in case of exception copying asyncronushly
await File(filepath).copy(renamePath);
}
}
}
}
static Future<File> _moveFile(File sourceFile, String newPath) async {
try {
// prefer using rename as it is probably faster
return await sourceFile.rename(newPath);
} on FileSystemException catch (e) {
// if rename fails, copy the source file and then delete it
final newFile = await sourceFile.copy(newPath);
await sourceFile.delete();
return newFile;
}
}
}
I've tried it and it works, so remember to update the permissions on the AndroidManifest file and you're all set.

Java, know if a file is inside a folder

Hi guys I'm trying to find if a specific file is inside the project directory.
File f = new File(System.getProperty("user.dir"));
System.out.println(f);
String archivoLiga="LigaV2";
System.out.println(f.listFiles((dir1, name) -> name.startsWith(archivoLiga) && name.endsWith(".properties")).length == 0);
But this only works if the file is in the "first" level, i want it to find it even if it's inside another folder. Any ideas?
Use Java 8's find() method to recurse subdirectories:
final int MAX_DEPTH = 50; // Max depth of subdirectories to search
Path userDir = Paths.get(System.getProperty("user.dir"));
System.out.println(userDir);
String archivoLiga="LigaV2";
System.out.println(
Files.find(
userDir,
maxDepth,
(path,attr) -> path.getFileName().startsWith(archivoLiga)
&& path.getFileName().endsWith(".properties"))
.findAny()
.isPresent());
Try recursively looking inside subfolders :-
public boolean checkForFile(String dirname,String prefix,String ext){
File dir = new File(dirname);
//System.out.println(dir);
for(File f : dir.listFiles()){
if(f.isFile()){
if(f.getName().startsWith(prefix) && f.getName().endsWith(ext)){
System.out.println(f.getName());
return true;
}
}
else{
//This step starts looking inside subfolder as well
return checkForFile(f.getAbsolutePath(),prefix,ext);
}
}
return true;
}
To check a file inside a folder, You will need to use exists() method of java.io.File like this:
boolean exists = new File("FOLDER_PATH/FILE_NAME").exists();
if (exists) {
System.out.println("File exists inside given folder");
} else {
System.out.println("File does not exists inside given folder");
}
Also possible with FileVisitor:
#Getter #Setter
#RequiredArgsConstructor
public static class SearchVisitor extends SimpleFileVisitor<Path> {
private final String fileToSearch;
private boolean found=false;
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if(!file.getFileName().toString().equals(fileToSearch)) return FileVisitResult.CONTINUE;
found=true;
return FileVisitResult.TERMINATE;
}
}
public void test() throws IOException {
SearchVisitor sv = new SearchVisitor("LigaV2");
Files.walkFileTree( Paths.get(System.getProperty("user.dir")), sv);
log.info("found file {}:{}", sv.getFileToSearch(), sv.isFound());
}
Use public boolean isDirectory() in java file API following is the link to oracle documentation. Tests whether the file denoted by this abstract pathname is a directory.
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory()

How to read all mp3 files in my computer in java?

My aim is to get list of all mp3 files in my computer(below code in c: directory). But when I run this code, I am getting NullPointerException. But works well for other directory like(e:).
public class music {
public static void main(String args[]){
extract("c:\\");
}
public static void extract(String p){
File f=new File(p);
File l[]=f.listFiles();
for(File x:l)
{
//System.out.println(x.getName());
if(x.isHidden()||!x.canRead())
continue;
if(x.isDirectory())
extract(x.getPath());
else if(x.getName().endsWith(".mp3"))
System.out.println(x.getPath()+"\\"+x.getName());
}
}
}
I got NPE with your code when it tried to access some not real directories like c:\Documents and Settings.
To solve this problem you can skip iterating over directories that returns null from listFiles() like in this code:
public static void main(String args[]) {
extract(new File("c:\\"));
}
public static void extract(File dir) {
File l[] = dir.listFiles();
if (l == null) {
System.out.println("[skipped] " + dir);
return;
}
for (File x : l) {
if (x.isDirectory())
extract(x);
if (x.isHidden() || !x.canRead())
continue;
else if (x.getName().endsWith(".mp3"))
System.out.println(x.getPath());//name should be included in path
}
}
In Windows operating system. C Drive (Windows drive) have system file that used by windows while running and some file that locked by windows. When your code try to access that files its through exception.
Try to run this code with other then C:// drive..
Add Try catch or null check for this files:
import java.io.*;
public class Music {
public static void main(String args[]){
extract("c:\\");
}
public static void extract(String p){
File f=new File(p);
File l[]=f.listFiles();
for(File x:l){
if(x==null) return;
if(x.isHidden()||!x.canRead()) continue;
if(x.isDirectory()) extract(x.getPath());
else if(x.getName().endsWith(".mp3"))
System.out.println(x.getPath()+"\\"+x.getName());
}
}
}

How to check if a folder exists?

I am playing a bit with the new Java 7 IO features. Actually I am trying to retrieve all the XML files in a folder. However this throws an exception when the folder does not exist. How can I check if the folder exists using the new IO?
public UpdateHandler(String release) {
log.info("searching for configuration files in folder " + release);
Path releaseFolder = Paths.get(release);
try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){
for (Path entry: stream){
log.info("working on file " + entry.getFileName());
}
}
catch (IOException e){
log.error("error while retrieving update configuration files " + e.getMessage());
}
}
Using java.nio.file.Files:
Path path = ...;
if (Files.exists(path)) {
// ...
}
You can optionally pass this method LinkOption values:
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
There's also a method notExists:
if (Files.notExists(path)) {
Quite simple:
new File("/Path/To/File/or/Directory").exists();
And if you want to be certain it is a directory:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
To check if a directory exists with the new IO:
if (Files.isDirectory(Paths.get("directory"))) {
...
}
isDirectory returns true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.
See: documentation.
Generate a file from the string of your folder directory
String path="Folder directory";
File file = new File(path);
and use method exist.
If you want to generate the folder you sould use mkdir()
if (!file.exists()) {
System.out.print("No Folder");
file.mkdir();
System.out.print("Folder created");
}
You need to transform your Path into a File and test for existence:
for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}
There is no need to separately call the exists() method, as isDirectory() implicitly checks whether the directory exists or not.
import java.io.File;
import java.nio.file.Paths;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
}
public static boolean isFileDirectoryExists(File file)
{
if (file.exists())
{
return true;
}
return false;
}
public static boolean isDirectoryExists(String directoryPath)
{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}
}
We can check files and thire Folders.
import java.io.*;
public class fileCheck
{
public static void main(String arg[])
{
File f = new File("C:/AMD");
if (f.exists() && f.isDirectory()) {
System.out.println("Exists");
//if the file is present then it will show the msg
}
else{
System.out.println("NOT Exists");
//if the file is Not present then it will show the msg
}
}
}
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;
From SonarLint, if you already have the path, use path.toFile().exists() instead of Files.exists for better performance.
The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.
The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile.
Noncompliant Code Example:
Path myPath;
if(java.nio.Files.exists(myPath)) { // Noncompliant
// do something
}
Compliant Solution:
Path myPath;
if(myPath.toFile().exists())) {
// do something
}

Can't load a BufferedImage

I have a form with that code:
public Form()
{
initComponents();
try
{
File file= new File("avatar.jpg");
BufferedImage image= ImageIO.read(file);
}
catch (IOException ex)
{
System.out.println("Failed to load image");
}
}
The problem is that the code always throws the IOException and enters in the catch block.
So the file isn't read.
I have created the project with Netbeans 7.2, and the directory looks like this:
What's the problem? Maybe the file shouldn't be there but in the father directory? Or what?
Is your image being packaged within your jar? to find this out, extract you jar file like you would an ordinary zip file and check if the image is anywhere there (normally located by jarname\packagename\filename. If so then you'll need to extract your image as a resource using getResourceAsStream().
It would be something like:
public class Test {
private static final String absName = "/yourpackage/yourimage.jpg";
public static void main(String[] args) {
Class c=null;
try {
c = Class.forName("yourpackage.Test");//pkg is the package name in which the resource lies
} catch (Exception ex) {
// This should not happen.
}
InputStream s = c.getResourceAsStream(absName);
// do something with it.
}
public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResourceAsStream(name); // A system class.
}
return cl.getResourceAsStream(name);
}
public java.net.URL getResource(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResource(name); // A system class.
}
return cl.getResource(name);
}
private String resolveName(String name) {
if (name == null) {
return name;
}
if (!name.startsWith("/")) {
Class c = this;
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/') + "/" + name;
}
} else {
name = name.substring(1);
}
return name;
}
}
Reference:
Accessing Resources
It looks like you have a namespace of poker.*
It all depends on where the jvm is initialized from.
Where is your main? Is it in /Users/ramy/NetBeansProjects/Poker/src?
Also, I suggest you use getResource() for all of your file loading needs, especially inside jars.
this.getClass().getResource("/resource/buttons1.png")
or
this.getClass().getResourceAsStream("/resource/TX_Jello2.ttf")
You can find out where your programs default path is by doing the following:
System.getProperty("user.dir");
Without seeing the error I would say the most likely cause is it can't find the file. So I suggest you replace "avatar.jpg" in the File constructor with the absolute file path to it. e.g.
File file = new File("INSERT_PATH_TO_FILE/avatar.jpg");
You cannot assume the image will be "there" because the relative path between your .java and the image seems ok.
Accessing a resource depends of your "kind" of project (Web, standalone....). In your case, you can try to get the image from your classpath
final File inputFile = new ClassPathResource("....").getFile();
final BufferedImage inputImg = ImageIO.read(inputFile);

Categories

Resources