public static void fileSearcher() throws IOException {
File dire = new File ("C:/");
String[] allFile = dire.list();
for (int i = 0;i<10;i++) {
String FilIn = allFile[i]; // here is where I need to scan entire pc for file
if(FilIn.equals("eclipse.exe")){
System.out.println("Found Eclipse!");
break;
}
else {
System.out.println("Eclipse not found on local drive.");
}
Is there a simple way to scan an entire HHD/SSD for a specific file ?
This will do the job for you and it works too when there are multiple drives or partitions. It will also search for additional files with that same name.
import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class HardDiskSearcher {
private static boolean fileFound = false;
private static String searchTerm = "eclipse.exe";
public static void main(String[] args) {
fileFound = false;
File[] systemRoots = File.listRoots();
FileSystemView fsv = FileSystemView.getFileSystemView();
for (File root: systemRoots) {
if (fsv.getSystemTypeDescription(root).equals("Local Disk")) {
File[] filesFromRoot = root.listFiles();
recursiveSearch(searchTerm, filesFromRoot);
}
}
System.out.println("File you searched for was found? : " + fileFound);
}
private static void recursiveSearch(String searchTerm, File... files) {
for (File file: files) {
if (file.isDirectory()) {
File[] filesInFolder = file.listFiles();
if (filesInFolder != null) {
for (File f : filesInFolder) {
if (f.isFile()) {
if (isTheSearchedFile(f, searchTerm)) {
fileFound = true;
}
}
}
for (File f : filesInFolder) {
if (f.isDirectory()) {
recursiveSearch(searchTerm, f);
}
}
}
}
else if (isTheSearchedFile(file, searchTerm)) {
fileFound = true;
}
}
}
private static boolean isTheSearchedFile(File file, String searchTerm) {
if (file.isFile() && (searchTerm.equals(file.getName())) ) {
System.out.println("The file you searched for has been found! " +
"It was found at: " + file.getAbsolutePath());
return true;
}
return false;
}
}
I am not 100% sure about why the if-statement (filesInFolder != null) is necessary here but i suspect Windows returns null when trying to list files from specific system folder or something.
I have been trying to upload a file from java as well as postman. But I am unable to upload. The server is giving back the response as 200 Ok. But, the file is not being uploaded.
API Details:
I have an API for uploading file as "FileExplorerController". This API has a method "upload()" to upload the files. Url to access this method is"/fileupload". The API is working fine if I upload a file through HTML UI.
But I am trying to upload using Java. I have tried using Postman as well.
I have passed the multipart form data in several ways. But unable to resolve the issue. The code is as follows.
API - Upload - Function
public Result upload() {
String fileName="";
String folderPath="";
String fileDescription="";
String userName = "";
StopWatch stopWatch = null;
List<FileUploadStatusVo> fileStatus = new ArrayList<>();
try {
stopWatch = LoggerUtil.startTime("FileExplorerController -->
upload() : File Upload");
StringBuilder exceptionBuilder = new StringBuilder();
Http.MultipartFormData body =
play.mvc.Controller.request().body().asMultipartFormData();
Http.Context ctx = Http.Context.current();
userName = ctx.session().get(SessionUtil.USER_NAME);
String password = "";
if(StringUtils.isBlank(userName)) {
Map<String, String[]> formValues = play.mvc.Controller.
request().body().asMultipartFormData().asFormUrlEncoded();
if(formValues != null) {
if(formValues.get("userName") != null &&
formValues.get("userName").length > 0) {
userName = formValues.get("userName")[0];
}
if(formValues.get("password") != null &&
formValues.get("password").length > 0) {
password = formValues.get("password")[0];
}
}
if(StringUtils.isBlank(userName) ||
StringUtils.isBlank(password)) {
return Envelope.ok();
}
UserVo userVo = userService.findUserByEmail(userName);
boolean success = BCrypt.checkpw(password, userVo.password);
if(!success) {
return badRequest("Password doesn't match for the given user
name: "+userName);
}
if(userVo == null) {
return Envelope.ok();
}
}
boolean override = false;
String fileTags="";
boolean isPublicView = false;
boolean isPublicDownload = false;
boolean isPublicDelete = false;
boolean isEmailNotification = false;
boolean isEmailWithS3Link = false;
List<String> viewerGroupNames = new ArrayList<>();
List<String> downloaderGroupNames = new ArrayList<>();
List<String> deleterGroupNames = new ArrayList<>();
List<String> viewerUserNames = new ArrayList<>();
List<String> downloaderUserNames = new ArrayList<>();
List<String> deleterUserNames = new ArrayList<>();
List<String> emailIds = new ArrayList<>();
Map<String, String[]> formValues =
play.mvc.Controller.request().body().
asMultipartFormData().asFormUrlEncoded();
JSONObject obj = new JSONObject(formValues.get("model")[0]);
Set<String> groupNames = new HashSet<>();
Set<String> userNames = new HashSet<>();
if(obj != null) {
if(obj.get("override") != null) {
override = Boolean.valueOf(obj.get("override").toString());
}
if(obj.get("description") != null) {
fileDescription = obj.get("description").toString();
}
if(obj.get("tags") != null) {
fileTags = obj.get("tags").toString();
}
if(obj.get("folderPath") != null){
folderPath = obj.get("folderPath").toString();
} else {
folderPath =
ctx.session().get(SessionUtil.LOCAL_STORAGE_PATH);
}
if(obj.get("isPublicView") != null) {
isPublicView =
Boolean.parseBoolean(obj.get("isPublicView").toString());
}
if(obj.get("isPublicDownload") != null) {
isPublicDownload =
Boolean.parseBoolean(obj.get("isPublicDownload").toString());
}
if(obj.get("isPublicDelete") != null) {
isPublicDelete = Boolean.parseBoolean(
obj.get("isPublicDelete").toString());
}
if(obj.get("emailNotification") != null) {
isEmailNotification =
Boolean.parseBoolean(obj.get("emailNotification").toString());
}
if(obj.get("emailWithFileAttachement") != null) {
isEmailWithS3Link =
Boolean.parseBoolean(obj.get(
"emailWithFileAttachement").toString());
}
if(obj.get("viewerGroupNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerGroupNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("downloaderGroupNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("deleteGroupNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("viewerUserNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerUserNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("downloaderUserNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("deleteUserNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("emailIds") != null) {
if(isEmailWithS3Link) {
String[] emailIdsArr =
(obj.get("emailIds").toString()).split(",");
for(String emailId:emailIdsArr){
if(StringUtils.isNotEmpty(emailId)){
emailIds.add(emailId);
}
}
}
}
}
if(groupNames.size() == 0 && userNames.size() == 0){
isEmailNotification = false;
}
List<Http.MultipartFormData.FilePart> files = body.getFiles();
boolean multiUpload = false;
if(files != null && files.size() > 1) {
multiUpload = true;
}
Logger.info("Total Number of files is to be uploaded:"+ files.size()
+" by user: " + userName);
int uploadCount = 0;
List<String> fileNames = new ArrayList<>();
List<String> fileMasters = new ArrayList<>();
FileMasterVo fileMasterVo = null;
UserVo userVo = userService.findUserByEmail(userName);
for(Http.MultipartFormData.FilePart uploadedFile: files) {
if (uploadedFile == null) {
return badRequest("File upload error for file " +
uploadedFile + " for file path: " + fileName);
}
uploadCount++;
String contentType = uploadedFile.getContentType();
String name = uploadedFile.getFile().getName();
Logger.info("Content Type: " + contentType);
Logger.info("File Name: " + fileName);
Logger.info("Name: " + name);
Logger.info("Files Processed : "+uploadCount+"/"+files.size()+"
for user: "+userName);
try {
String extension =
FileUtil.getExtension(uploadedFile.getFilename()).toLowerCase();
File renamedUploadFile =
FileUtil.moveTemporaryFile(System.getProperty("java.io.tmpdir"),
System.currentTimeMillis() + "_" +
uploadedFile.getFilename(), uploadedFile.getFile());
FileInputStream fis = new
FileInputStream(renamedUploadFile);
String errorMsg = "";
fileName = folderPath + uploadedFile.getFilename();
fileNames.add(uploadedFile.getFilename());
if(multiUpload) {
Logger.info("Attempting to upload file " + folderPath +
"/" + uploadedFile.getFilename());
fileMasterVo = fileService.upload(folderPath,fileName,
fileDescription, new Date(), fis, fis.available(),
extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else if(fileName != null) {
Logger.info("Attempting to upload file " + fileName);
int index = fileName.lastIndexOf("/");
if (index > 1) {
fileMasterVo =
fileService.upload(folderPath,fileName, fileDescription,
new Date(), fis, fis.available(), extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else {
errorMsg = "Root Folder MUST exist to upload any
file";
return badRequest(errorMsg);
}
} else {
errorMsg = "File Name is incorrect";
return badRequest(errorMsg);
}
createFileActivityLog(
fileMasterVo,userVo,ViewConstants.UPLOADED);
if (fileMasterVo != null && fileMasterVo.getId() != null) {
fileMasters.add(fileMasterVo.getId().toString());
}
} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
exceptionBuilder.append("Exception occured in uploading
file: ");
exceptionBuilder.append(name);
exceptionBuilder.append(" are as follows ");
exceptionBuilder.append(ExceptionUtils.getStackTrace(inEx));
}
fileStatus.add(new
FileUploadStatusVo(uploadedFile.getFilename(),
fileMasterVo.getStatus()));
}
if(isEmailNotification){
fileService.sendNotificationForFile(folderPath,fileNames,
userName, groupNames,
userNames, ViewConstants.UPLOADED);
}
if (isEmailWithS3Link) {
//fileService.sendFileS3Link(folderPath, emailIds, fileMasters);
// Replacing sending S3 link with sending cdi specific link
fileService.sendFilesLink(emailIds, fileMasters);
}
String exceptions = exceptionBuilder.toString();
LoggerUtil.endTime(stopWatch);
if(!StringUtils.isBlank(exceptions)) {
Logger.error("Exception occured while uploading file: " +
fileName + " are as follows " + exceptions);
}
return Envelope.ok(fileStatus);
} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
return badRequest("There is a system error please contact
support/administrator" );
} }
Client
**Client - Program**
multipart.addFormField("fileName",file.getAbsolutePath());
multipart.addFormField("folderPath","D/");
multipart.addFormField("fileDescription","Desc");
multipart.addFormField("userName","superadmin");
multipart.addFormField("password","admin");
multipart.addFormField("override","false");
multipart.addFormField("fileTags","tag");
multipart.addFormField("isPublicView","true");
multipart.addFormField("isPublicDownload","true");
multipart.addFormField("isPublicDelete","false");
multipart.addFormField("isEmailNotification","false");
multipart.addFormField("isEmailWithS3Link","true");*/
multipart.addFormField("file", input);
System.out.print("SERVER REPLIED: ");
for (String line : response)
{
System.out.print(line);
}
// synchronize(clientFolder, uploadFolder, true);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
I am able to upload using the following code snippet.
Here "model" is a json object which contain all parameters.
DefaultHttpClient client = new DefaultHttpClient();
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("userName", userName)
.addTextBody("password", passWord)
.addBinaryBody("upload_file", new File(sourceFolder + "/" + fileName), ContentType.create("application/octet-stream"), fileName)
.addTextBody("model", object.toString())
.build();
HttpPost post = new HttpPost(uploadURL);
post.setEntity(entity);
HttpResponse response = null;
try {
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
logger.info("File " + file.getName() + " Successfully Uploaded At: " + destination);
} else {
logger.info("File Upload Unsuccessful");
}
logger.info("Response from server:" + response.getStatusLine());
} catch (ClientProtocolException e) {
logger.error("Client Protocol Exception");
logger.error(e.getMessage());
I have the following code that is very rough but it's a start for what Ive been asked to accomplish. My question relates to the list that is generated. It currently lists all the files on the server and tags the PMR data as mentioned in the code. Is there something I can change so that the results generated only list the matching data instead of tagging it?
import java.io.File;
public class FilePmrDetector {
public static void main(String[] args) {
listFiles(new File("/"));
}
public static void listFiles(File file) {
if (file == null || isBlackListed(file)) {
return;
}
doSomeActionOnFile(file);
if (file.isDirectory()) {
File[] fs = file.listFiles();
if (fs != null) {
for (File f : fs) {
listFiles(f);
}
}
}
}
}
return false;
}
public static void doSomeActionOnFile(File file) {
String msg = file.getAbsolutePath();
if (isAPmr(file)) {
msg += " ----------PMR-----------";
}
System.out.println(msg);
}
public static boolean isAPmr(File file) {
if (file != null) {
String name = file.getAbsolutePath();
return name.matches("^.*(\\d{5},[a-zA-z0-9]{3},\\d{3}).*$");
}
return false;
}
}
This should be runable and it only prints if (isAPmr(file))
import java.io.File;
public class FilePmrDetector {
public static void main(String[] args) {
listFiles(new File("/"));
}
public static void listFiles(File file) {
if (file == null) {
return;
}
doSomeActionOnFile(file);
if (file.isDirectory()) {
File[] fs = file.listFiles();
if (fs != null) {
for (File f : fs) {
listFiles(f);
}
}
}
}
public static void doSomeActionOnFile(File file) {
String fileName = file.getAbsolutePath();
String printOut = "";
if (isAPmr(file)) {
printOut = printOut + fileName;
}
if (printOut != "") {
System.out.println(printOut);
}
}
public static boolean isAPmr(File file) {
if (file != null) {
String name = file.getAbsolutePath();
return name.matches("^.*(\\d{5},[a-zA-z0-9]{3},\\d{3}).*$");
// I tested with: return name.contains(".exe");
}
return false;
}
}
Edit:
This doSomeActionOnFile(File file) method is better because it is not overcomplicated like the other.
public static void doSomeActionOnFile(File file) {
if (isAPmr(file)) {
System.out.println(file.getAbsolutePath());
}
}
Here i have Folder(Books)in that i have 3 sub folders named:sub1, sub2, sub3 and sub1 have 2 files, sub2 have 3 files, sub3 have 4 files. And sub1.zip,sub2.zip and sub3.zip. I want to keep only zip files and delete sub1, sub2, sub3 folders of Books. With my code I'm able to delete all inside files of sub1 folder, sub2, sub3 finally all folders becoming empty, then how can I delete sub1,sub2 and sub3 folders.
public void SaveZipFiles(File destwithouAudio) throws IOException {
File[] listOfFiles = destwithouAudio.listFiles();
for (File listOfFile : listOfFiles) {
if (listOfFile.getName().endsWith(".zip")) {
} else {
File FolderInside = new File(listOfFile.getAbsolutePath());
File[] listOfFilesInside = FolderInside.listFiles();
for (File listOfFilesInside1 : listOfFilesInside) {
File deleteFolder = new File(listOfFilesInside1.getAbsolutePath());
//System.out.println(""+listOfFilesInside[j]);
RecursiveDelete(deleteFolder);
}
}
}
}
RecursiveDelete method code is:
public static void RecursiveDelete(File file) throws IOException {
if (file.isDirectory()) {
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
} else {
String files[] = file.list();
for (String temp : files) {
File fileDelete = new File(file, temp);
RecursiveDelete(fileDelete);
}
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
}
}
} else {
file.delete();
System.out.println("File is deleted : " + file.getAbsolutePath());
}
}
After deleting all files from sub1,sub2,sub3 foldersIi need to delete all sub1,sub2,sub3 folders.
Where to change the code?
public void deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete(); // The directory is empty now and can be deleted.
}
then, you could be using
public void SaveZipFiles(File destwithouAudio) {
File[] deletion = destwithouAudio.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return !name.endsWith(".zip");
}
});
for (File toDelete : deletion) {
deleteDir(toDelete);
}
}
(using deleting folder from java folder deletion)
public void checkfile (String serverName) throws Exception {
if (serverName == null)
serverName = "";
System.out.println("IN Check file method");
File folder = new File("D:\\MVXOUT412"); //Path on the server
int count = 0;
String abc;
File[] files = folder.listFiles();
if (files != null) {
System.out.println("IN IF method");
for (int i=0;i<files.length ;i++) {
count++;
abc = files[i].getName();
System.out.println("Number of files: " + count);
System.out.println("Name of files: " + abc);
}
}
}
This code is showing only some files at path/folder on the server. Other files can't be viewed. Login and logout happens successfully.
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);