Optimising Java Scanner to match regex in file faster - java

I am currently using this code to match a regex against a lot of files, however, this is fairly slow. Is there a way I can do the same thing, but faster?
public class Filter {
private String title;
private String regex;
private List<String> results = new LinkedList<String>();
...
}
I have a few Filters for different types of regexes, they range from matching emails to matching words like apikey, ... The code will be used to scan for vulnerabilities in decompiled classes and other text based files.
My code also only checks for 1 match in a file, I'd like to get all matches.
public void startScans() {
List<File> files = getAllFiles(getFolder()); //Gets a list of all text based files in a folder
for (int i = 0; i < files.size(); i++) {
for(Filter filter : getFilters()) {
try {
System.out.print("\rScanning file " + i + " out of " + files.size() + " using filter " + filter.getTitle() + "...");
scanFile(files.get(i), filter);
} catch (FileNotFoundException ignored) {}
}
}
}
private void scanFile(File f, Filter filter) throws FileNotFoundException {
Scanner scanner = new Scanner(f);
String result = scanner.findWithinHorizon(filter.getRegex(), 0);
if (result != null) {
filter.addResult(result);
}
scanner.close();
}

You can also use an external tool if you want a faster execution, that is, execute a command. e.g.
Windows: findstr /R [a-z]*xyz *
Linux: egrep -R "[a-z]*xyz" .
NOTE: You can run these commands from Java.

Related

How to get PID of a process running in Windows using Java

I have used OSHI libraries available, but the getProcessID function is not working. I need to find the PID of a process entered by the user.
I have now used this code
public static String getProcessPID(String processName, boolean... ignoreLetterCase) {
String pid = "";
boolean ignoreCase = true;
if (ignoreLetterCase.length > 0) {
ignoreCase = ignoreLetterCase[0];
}
// Acquire the Task List from Windows
ProcessBuilder processBuilder = new ProcessBuilder("tasklist.exe");
Process process;
try {
process = processBuilder.start();
}
catch (java.io.IOException ex) {
return "";
}
// Read the list and grab the desired PID
String tasksList;
try (Scanner scanner = new Scanner(process.getInputStream(), "UTF-8").useDelimiter("\\A")) {
int counter = 0;
String strg = "";
while (scanner.hasNextLine()) {
strg = scanner.nextLine();
// Uncomment the line below to print the current Tasks List to Console Window.
// System.out.println(strg);
if (!strg.isEmpty()) {
counter++;
if (counter > 2) {
if (ignoreCase) {
if (strg.toLowerCase().contains(processName.toLowerCase())) {
String[] tmpSplit = strg.split("\\s+");
pid += (pid.isEmpty()) ? tmpSplit[1] : ", " + tmpSplit[1];
}
}
else {
if (strg.contains(processName)) {
String[] tmpSplit = strg.split("\\s+");
pid += (pid.isEmpty()) ? tmpSplit[1] : ", " + tmpSplit[1];
}
}
}
}
}
}
return pid;
}
This fails for processes with multiple instances running such as Chrome. So, how do I get Parent ProcessID or a process with a space in between the name?
Don’t use tasklist.exe. Use the ProcessHandle class. Not only will your code be shorter and easier to maintain, it will also work on systems other than Windows, with no additional effort.
Also, don’t use a varargs argument when you only want zero or one values. Use method overloads for that.
public static OptionalLong getProcessPID(String processName) {
return getProcessPID(processName, true);
}
public static OptionalLong getProcessPID(String processName, boolean ignoreLetterCase) {
Predicate<String> matcher = cmd -> (ignoreLetterCase
? cmd.toLowerCase().contains(processName.toLowerCase())
: cmd.contains(processName));
try (Stream<ProcessHandle> processes = ProcessHandle.allProcesses()) {
return processes
.filter(p -> p.info().command().filter(matcher).isPresent())
.mapToLong(p -> p.pid())
.findFirst();
}
}

Listing files in ftp server without the use of recursion [duplicate]

I'm trying to produce file listing of a given directory and it's sub directories in a ftp server.
The server works fine, and I have been successfully able to produce the file listing of the current directory. When I try to list the subdirectories and their files is where it gets complicated.
I was asked not to use a recursion algorithm, so I did some research of my own. I have tried using threads (for every directory found, start a new thread), but I wasn't able to keep my connection stable and open. Any ideas on how to do so correctly with threads, or other alternatives?
EDIT: below is my code, when using the recursive statement (last line of code), it works
class TEST {
public static synchronized void main(String[] args) {
String server = args[0]; //server,path will be given as an arguments
String pass = "SOMEPASS";
String user = "SOMEUSER";
int port = 21;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Connect failed");
return;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
}
/*START THE FILE LISTING HERE*/
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
} finally {
// logs out and disconnects from server
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
private static void scanDir(FTPClient client, String path) throws IOException {
FTPFile[] files = client.listFiles(path); // Search all the files in the current directory
for (int j = 0; j < files.length; j++) {
System.out.println(files[j].getName()); // Print the name of each files
}
FTPFile[] directories = client.listDirectories(path); // Search all the directories in the current directory
for (int i = 0; i < directories.length; i++) {
String dirPath = directories[i].getName();
System.out.println(dirPath); // Print the path of a sub-directory
scanDir(client,dirPath); // Call recursively the method to display the files in the sub-directory DONT WANT TO DO THAT...
}
}
}
Okay, here is an example of how to handle it non-recursively, but with lists.
Mind, that this example is based on /accessing the local filesystem, but can easily be rewritten/extended for any kind of hierarchial/recursive structure.
package stackoverflow.nonrecursivefilesearch;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.stream.Stream;
public class NonRecursiveFileSearch {
public static void main(final String[] args) throws IOException {
final File searchDir = new File("D:\\test\\maven-test"); // set one
System.out.println("\nOld Java");
printDirs(listFiles_old(searchDir, true, true), "OLD: Depth first, include dirs");
printDirs(listFiles_old(searchDir, true, false), "OLD: Breadth first, include dirs");
printDirs(listFiles_old(searchDir, false, true), "OLD: Depth first, exclude dirs");
printDirs(listFiles_old(searchDir, false, false), "OLD: Breadth first, exclude dirs");
System.out.println("\nNew java.io with streams");
printDirs(listFiles_newIO(searchDir, true), "Java NIO, include dirs");
printDirs(listFiles_newIO(searchDir, false), "Java NIO, exclude dirs");
}
/**
* this is the way to 'manually' find files in hierarchial/recursive structures
*
* reminder: "Depth First" is not a real depth-first implementation
* real depth-first would iterate subdirs immediately.
* this implementation iterates breadth first, but descends into supdirs before it handles same-level directories
* advantage of this implementation is its speed, no need for additional lists etc.
*
* in case you want to exclude recursion traps made possible by symbolic or hard links, you could introduce a hashset/treeset with
* visited files (use filename strings retrieved with canonicalpath).
* in the loop, check if the current canonical filename string is contained in the hash/treeset
*/
static public ArrayList<File> listFiles_old(final File pDir, final boolean pIncludeDirectories, final boolean pDepthFirst) {
final ArrayList<File> found = new ArrayList<>();
final ArrayList<File> todo = new ArrayList<>();
todo.add(pDir);
while (todo.size() > 0) {
final int removeIndex = pDepthFirst ? todo.size() - 1 : 0;
final File currentDir = todo.remove(removeIndex);
if (currentDir == null || !currentDir.isDirectory()) continue;
final File[] files = currentDir.listFiles();
for (final File file : files) {
if (file.isDirectory()) {
if (pIncludeDirectories) found.add(file);
// additional directory filters go here
todo.add(file);
} else {
// additional file filters go here
found.add(file);
}
}
}
return found;
}
static private void printDirs(final ArrayList<File> pFiles, final String pTitle) {
System.out.println("====================== " + pTitle + " ======================");
for (int i = 0; i < pFiles.size(); i++) {
final File file = pFiles.get(i);
System.out.println(i + "\t" + file.getAbsolutePath());
}
System.out.println("============================================================");
}
/**
* this is the java.nio approach. this is NOT be a good solution for cases where you have to retrieve/handle files in your own code.
* this is only useful, if the any NIO class provides support. in this case, NIO class java.nio.file.Files helps handling local files.
* if NIO or your target system does not offer such helper methods, this way is harder to implement, as you have to set up the helper method yourself.
*/
static public Stream<Path> listFiles_newIO(final File pDir, final boolean pIncludeDirectories) throws IOException {
final Stream<Path> stream = Files.find(pDir.toPath(), 100,
(path, basicFileAttributes) -> {
final File file = path.toFile(); // conversion to File for easier access (f.e. isDirectory()), could also use NIO methods
return (pIncludeDirectories || !file.isDirectory() /* additional filters go here */ );
});
return stream;
}
static private void printDirs(final Stream<Path> pStream, final String pTitle) {
System.out.println("====================== " + pTitle + " ======================");
pStream.forEach(System.out::println);
System.out.println("============================================================");
}
}
AND, one must add, java.nio.file.Files.find() might be implemented recursively. But as it's just one call, this maybe could count as 'non-recursive' too.
ALSO, as the OP stated in comments, one might use Stack or other FIFO/LIFO collections. LIFO for a mixed depth-first, FIFO for breadth-first approach.

How to extract Full Name From a Url in Java

i need a library to extract file's full name from it's URL(Direct Download Link). I want a powerful library. I use FileNameUtils from Apache commons, But this class does not support a lot of URLs.
I want a library which supports these Urls:
https://example.cdn.com/mp4/7/9/5/file_795f32460d111df334849ee8336e56ca.mp4?e=1535545105&h=4772d27a70cd9b1c665b712f62592c47&download=1
name : file_795f32460d111df334849ee8336e56ca.mp4
http://example.cdn.comr/post/93/3/Jozve-Kamele-arbi.abp.zip
name : Jozve-Kamele-arbi.abp.zip
http://cdl.example.com/?b=dl-software&f=Windows.8.1.Enterprise.x86.Aug.2018_n.part1.rar
name : dl-software&f=Windows.8.1.Enterprise.x86.Aug.2018_n.part1.rar
https://www.google.com/url?sa=t&source=web&rct=j&url=http://www.pdf995.com/samples/pdf.pdf&ved=2ahUKEwjV096X-ZHdAhVQzlkKHTpUBV4QFjAAegQIARAB&usg=AOvVaw3HFvAQ7GNf5QjsUo05ot-j
name: pdf.pdf
Can anyone help me? Thanks.
I apologize in advance if the grammar of my sentence is not correct. because I can't speak English well.
You could actually also try to solve this problem with regular expressions (like e.g (?i)([^=/&?]+\\.(" + EXTENSIONS + "))\\b), if you have a list of the files extensions you are interested in.
Here is an example of such a method which extracts a file from a URL:
private static final String EXTENSIONS = "ez|aw|atom|atomcat|atomsvc|ccxml|cdmia|cdmic|cdmid|cdmio|cdmiq|cu|davmount|dbk|dssc|xdssc|ecma|emma|epub|exi|pfr|gml|gpx|gxf|stk|ipfix|jar|ser|class|js|json|jsonml|lostxml|hqx|cpt|mads|mrc|mrcx|mathml|mbox|mscml|metalink|meta4|mets|mods|mp4s|mp4|mxf|oda|opf|ogx|omdoc|oxps|xer|pdf|pgp|prf|p10|p7s|p8|ac|cer|crl|pkipath|pki|pls|cww|pskcxml|rdf|rif|rnc|rl|rld|rs|gbr|mft|roa|rsd|rss|rtf|sbml|scq|scs|spq|spp|sdp|setpay|setreg|shf|rq|srx|gram|grxml|sru|ssdl|ssml|tfi|tsd|plb|psb|pvb|tcap|pwn|aso|imp|acu|air|fcdt|xdp|xfdf|ahead|azf|azs|azw|acc|ami|apk|cii|fti|atx|mpkg|m3u8|swi|iota|aep|mpm|bmi|rep|cdxml|mmd|cdy|cla|rp9|c11amc|c11amz|csp|cdbcmsg|cmc|clkx|clkk|clkp|clkt|clkw|wbs|pml|ppd|car|pcurl|dart|rdz|fe_launch|dna|mlp|dpg|dfac|kpxx|ait|svc|geo|mag|nml|esf|msf|qam|slt|ssf|ez2|ez3|fdf|mseed|gph|ftc|fnc|ltf|fsc|oas|oa2|oa3|fg5|bh2|ddd|xdw|xbd|fzs|txd|ggb|ggt|gxt|g2w|g3w|gmx|kml|kmz|gac|ghf|gim|grv|gtm|tpl|vcg|hal|zmm|hbci|les|hpgl|hpid|hps|jlt|pcl|pclxl|sfd-hdstx|mpy|irm|sc|igl|ivp|ivu|igm|i2g|qbo|qfx|rcprofile|irp|xpr|fcs|jam|rms|jisp|joda|karbon|chrt|kfo|flw|kon|ksp|htke|kia|sse|lasxml|lbd|lbe|123|apr|pre|nsf|org|scm|lwp|portpkg|mcd|mc1|cdkey|mwf|mfm|flo|igx|mif|daf|dis|mbk|mqy|msl|plc|txf|mpn|mpc|xul|cil|cab|xlam|xlsb|xlsm|xltm|eot|chm|ims|lrm|thmx|cat|stl|ppam|pptm|sldm|ppsm|potm|docm|dotm|wpl|xps|mseq|mus|msty|taglet|nlu|nnd|nns|nnw|ngdat|n-gage|rpst|rpss|edm|edx|ext|odc|otc|odb|odf|odft|odg|otg|odi|oti|odp|otp|ods|ots|odt|odm|ott|oth|xo|dd2|oxt|pptx|sldx|ppsx|potx|xlsx|xltx|docx|dotx|mgp|dp|esa|paw|str|ei6|efif|wg|plf|pbd|box|mgz|qps|ptid|bed|mxl|musicxml|cryptonote|cod|rm|rmvb|link66|st|see|sema|semd|semf|ifm|itp|iif|ipk|mmf|teacher|dxp|sfs|sdc|sda|sdd|smf|sgl|smzip|sm|sxc|stc|sxd|std|sxi|sti|sxm|sxw|sxg|stw|svd|xsm|bdm|xdm|tao|tmo|tpt|mxs|tra|utz|umj|unityweb|uoml|vcx|vis|vsf|wbxml|wmlc|wmlsc|wtb|nbp|wpd|wqd|stf|xar|xfdl|hvd|hvs|hvp|osf|osfpvg|saf|spf|cmp|zaz|vxml|wgt|hlp|wsdl|wspolicy|7z|abw|ace|dmg|aam|aas|bcpio|torrent|bz|vcd|cfs|chat|pgn|nsc|cpio|csh|dgc|wad|ncx|dtb|res|dvi|evy|eva|bdf|gsf|psf|pcf|snf|arc|spl|gca|ulx|gnumeric|gramps|gtar|hdf|install|iso|jnlp|latex|mie|application|lnk|wmd|wmz|xbap|mdb|obd|crd|clp|mny|pub|scd|trm|wri|nzb|p7r|rar|ris|sh|shar|swf|xap|sql|sit|sitx|srt|sv4cpio|sv4crc|t3|gam|tar|tcl|tex|tfm|obj|ustar|src|fig|xlf|xpi|xz|xaml|xdf|xenc|dtd|xop|xpl|xslt|xspf|yang|yin|zip|adp|s3m|sil|eol|dra|dts|dtshd|lvp|pya|ecelp4800|ecelp7470|ecelp9600|rip|weba|aac|caf|flac|mka|m3u|wax|wma|rmp|wav|xm|cdx|cif|cmdf|cml|csml|xyz|ttc|otf|ttf|woff|woff2|bmp|cgm|g3|gif|ief|ktx|png|btif|sgi|psd|sub|dwg|dxf|fbs|fpx|fst|mmr|rlc|mdi|wdp|npx|wbmp|xif|webp|3ds|ras|cmx|ico|sid|pcx|pnm|pbm|pgm|ppm|rgb|tga|xbm|xpm|xwd|dae|dwf|gdl|gtw|mts|vtu|appcache|css|csv|n3|dsc|rtx|tsv|ttl|vcard|curl|dcurl|mcurl|scurl|sub|fly|flx|gv|3dml|spot|jad|wml|wmls|java|nfo|opml|etx|sfv|uu|vcs|vcf|3gp|3g2|h261|h263|h264|jpgv|ogv|dvb|fvt|pyv|viv|webm|f4v|fli|flv|m4v|mng|vob|wm|wmv|wmx|wvx|avi|movie|smv|ice";
private static final Pattern FILE_DETECT = Pattern.compile("(?i)([^=/&?]+\\.(" + EXTENSIONS + "))\\b");
public static Optional<String> extractFileFrom(String url) {
Matcher matcher = FILE_DETECT.matcher(url);
return (matcher.find()) ? Optional.of(matcher.group(1)) : Optional.empty();
}
And here is a test which demonstrates how to use the method above:
public static void main(String[] args) throws ParseException {
List<String> strings = Arrays.asList(
"https://example.cdn.com/mp4/7/9/5/file_795f32460d111df334849ee8336e56ca.mp4?e=1535545105&h=4772d27a70cd9b1c665b712f62592c47&download=1",
"http://example.cdn.comr/post/93/3/Jozve-Kamele-arbi.abp.zip",
"http://cdl.example.com/?b=dl-software&f=Windows.8.1.Enterprise.x86.Aug.2018_n.part1.rar",
"https://www.google.com/url?sa=t&source=web&rct=j&url=http://www.pdf995.com/samples/pdf.pdf&ved=2ahUKEwjV096X-ZHdAhVQzlkKHTpUBV4QFjAAegQIARAB&usg=AOvVaw3HFvAQ7GNf5QjsUo05ot-j",
"https://www.google.com/url?sa=t&source=web&rct=j&url=http://www.pdf995.com/samples/pdf.PDF&ved=2ahUKEwjV096X-ZHdAhVQzlkKHTpUBV4QFjAAegQIARAB&usg=AOvVaw3HFvAQ7GNf5QjsUo05ot-j");
strings.stream().map(s -> extractFileFrom(s)).collect(Collectors.toList())
.forEach(System.out::println);
}
If you execute the main method you will see this on the console:
Optional[file_795f32460d111df334849ee8336e56ca.mp4]
Optional[Jozve-Kamele-arbi.abp.zip]
Optional[Windows.8.1.Enterprise.x86.Aug.2018_n.part1.rar]
Optional[pdf.pdf]
Optional[pdf.PDF]
I use this method, hope it helps you too. It will parse from question marks, hash too.
public static String parseFileNameFromUrl(String url) {
if (url == null) {
return "";
}
try {
URL res = new URL(url);
String resHost = res.getHost();
if (resHost.length() > 0 && url.endsWith(resHost)) {
// handle ...example.com
return "";
}
} catch (MalformedURLException e) {
e.printStackTrace();
return "";
}
int startIndex = url.lastIndexOf('/') + 1;
int length = url.length();
// find end index for ?
int lastQuestionMarkPos = url.lastIndexOf('?');
if (lastQuestionMarkPos == -1) {
lastQuestionMarkPos = length;
}
// find end index for #
int lastHashPos = url.lastIndexOf('#');
if (lastHashPos == -1) {
lastHashPos = length;
}
// calculate the end index
int endIndex = Math.min(lastQuestionMarkPos, lastHashPos);
return url.substring(startIndex, endIndex);
}

Start user's standard mail client with attachment pre-attached

I'm looking for a way that my application can call the user's standard mail application (e.g. Outlook, Thunderbird, etc.). And give it an recipient address, the email text and an attachment.
So, basically the standard email application should pop up have the email ready for me (with recipient, text and attachment) and all that is left to do for me is pressing "send" in my outlook, thunderbird etc.
I've been googling for a while now, but I couldn't find a real solution.
I've been looking into mapi a bit but it seems like 1. it's deprecated and 2. it's mainly built for outlook.
Any help/suggestions/solutions greatly appreciated!
Edit: I have seen the question Start Mail-Client with Attachment but no working answer was provided there and also the question is more than 3 years old.
Edit: Other languages would be ok, too. Has to work on Windows XP, Vista, 7, 8 (both 32 and 64 bit)
UPDATE: It seems to be more difficult than I have thought it to be.
I've been looking into JMAPI, which apparently only works for 32bit Systems.
I've also seen the solutions on codeproject.org (here and here), but I somehow couldn't get them to work.
Now I'm trying to do it with command line:
1. Read user's default mail client
2. Call a batch file according to the email client. (Yes you have to write a batch file for every common mail client.
Example for outlook:
"outlook.exe" /a "F:\test.png" /m "test.test#test.test&cc=test#test.test&subject=subject123&body=Hello, how are you%%3F%%0D%%0Anew line"
--> see my provided answer for futher info on that method
So...
After days of research I gave up to get a general solution.
I came up with a solution working at least for the two most common clients (Thunderbird & Outlook)
My solution is basically calling the application from command line.
For those interested, here is my solution: (I haven't tested it cross platform - works on my old XP laptop though)
import java.io.IOException;
/*
:: Punctuation Hexadecimal equivalent
:: ----------------------------------------------
:: Space ( ) %20
:: Comma (,) %2C
:: Question mark (?) %3F
:: Period (.) %2E
:: Exclamation point (!) %21
:: Colon (:) %3A
:: Semicolon (;) %3B
:: Line feed %0A --> New line %0D%0A
:: Line break (ENTER key) %0D --> New line %0D%0A
*/
public class Main {
static String test = "hi";
private static String attachment;
private static String to;
private static String cc;
private static String subject;
private static String body;
public static void main (String[] args){
attachment = "F:\\pietquest.png";
to = "test#test.de";
cc = "a.b#c.de";
subject = "TestSubject 123";
body = "Hi, what\'s going on%0D%0Anew line";
body = replace(body);
subject = replace(subject);
String[] value = WindowsRegistry.readRegistry("HKEY_LOCAL_MACHINE\\SOFTWARE\\Clients\\Mail", "");
if (value[10].contains("Thunderbird")){
System.out.println("Thunderbird");
String[] pfad = WindowsRegistry.readRegistry("HKEY_LOCAL_MACHINE\\SOFTWARE\\Clients\\Mail\\Mozilla Thunderbird\\shell\\open\\command", "");
String Pfad = pfad[10] + " " + pfad[11];
String argument = Pfad + " /compose \"to=" + to + ",cc=" + cc + ",subject=" + subject + ",body=" + body + ",attachment=" + attachment + "\"";
// System.out.println(argument);
try {
Runtime.getRuntime().exec(argument);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (value[10].contains("Outlook")){
System.out.println("Outlook");
String[] pfad = WindowsRegistry.readRegistry(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Clients\\Mail\\Microsoft Outlook\\shell\\open\\command", "");
String Pfad = pfad[10];
String argument = Pfad + " /a " + attachment + " /m \"" + to
+ "&cc=" + cc + "&subject=" + subject + "&body=" + body + "\"";
// System.out.println(argument);
try {
Runtime.getRuntime().exec(argument);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String replace(String toReplace){
toReplace = toReplace.replace(" ", "%20");
toReplace = toReplace.replace(",", "%2C");
toReplace = toReplace.replace("?", "%3F");
toReplace = toReplace.replace(".", "%2E");
toReplace = toReplace.replace("!", "%21");
toReplace = toReplace.replace(":", "%3A");
toReplace = toReplace.replace(";", "%3B");
return toReplace;
}
}
and this is the Windows Registry Class: (got that from here)
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public class WindowsRegistry {
/**
*
* #param location path in the registry
* #param key registry key
* #return registry value or null if not found
*/
public static final String[] readRegistry(String location, String key){
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg query " +
'"'+ location);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
// Parse out the value
String[] parsed = reader.getResult().split("\\s+");
if (parsed.length > 1) {
return parsed;
}
} catch (Exception e) {}
return null;
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw= new StringWriter();
public StreamReader(InputStream is) {
this.is = is;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1)
sw.write(c);
} catch (IOException e) {
}
}
public String getResult() {
return sw.toString();
}
}
you can use C#: Example C# or java: Example Java
EDIT
You can use Boost for ssl and send email via smtp

Open file to view its content [duplicate]

This question already has answers here:
How to open a file with the default associated program
(4 answers)
Closed 9 years ago.
I have a files list. Lets say it looks:
String[] lst = new String[] {
"C:\\Folder\\file.txt",
"C:\\Another folder\\another file.pdf"
};
I need some method to open these files with default program for them, lets say "file.txt" with Notepad, "another file.pdf" with AdobeReader and so on.
Does anyone knows how?
There is a method to do this:
java.awt.Desktop.getDesktop().open(file);
JavaDoc:
Launches the associated application to open the file.
If the specified file is a directory, the file manager of the current platform is launched to open it.
The Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.
If you are using J2SE 1.4 o Java SE 5, the best option is:
for(int i = 0; i < lst.length; i++) {
String path = lst[i];
if (path.indexOf(' ') > 0) {
// Path with spaces
Runtime.getRuntime().exec("explorer \"" + lst[i] + "\"");
} else {
// Path without spaces
Runtime.getRuntime().exec("explorer " + lst[i]);
}
}
Just make sure the file is in the right location, and this should work fine.
try
{
File dir = new File(System.getenv("APPDATA"), "data");
if (!dir.exists()) dir.mkdirs();
File file = new File(dir"file.txt");
if (!file.exists()) System.out.println("File doesn't exist");
else Desktop.getDesktop().open(file);
} catch (Exception e)
{
e.printStackTrace();
}
I didn't know you have a String array now. So, this one uses regex to process the file list in the format you specified before. Ignore if not required.
If the file list is huge and you would prefer that the files open one by one cmd works great. If you want them to open all at once use explorer. Works only on Windows but then on almost all JVM versions. So, there's a trade-off to consider here.
public class FilesOpenWith {
static String listOfFiles = "{\"C:\\Setup.log\", \"C:\\Users\\XYZ\\Documents\\Downloads\\A B C.pdf\"}";
public static void main(String[] args) {
if (args != null && args.length == 1) {
if (args[0].matches("{\"[^\"]+\"(,\\s?\"[^\"]+\")*}")) {
listOfFiles = args[0];
} else {
usage();
return;
}
}
openFiles();
}
private static void openFiles() {
Matcher m = Pattern.compile("\"([^\"]+)\"").matcher(listOfFiles);
while (m.find()) {
try {
Runtime.getRuntime().exec("cmd /c \"" + m.group(1) + "\"");
// Runtime.getRuntime().exec("explorer \"" + m.group(1) + "\"");
} catch (IOException e) {
System.out.println("Bad Input: " + e.getMessage());
e.printStackTrace(System.err);
}
}
}
private static void usage() {
System.out.println("Input filelist format = {\"file1\", \"file2\", ...}");
}
}

Categories

Resources