Search for string in all files inside a Directory - java

I want to search for particular string inside all files in a Directory.
Ex: Search for "tiger" in path D:/test/chapters/
D:/test/chapters
/chapter1.log
/chapter2.log
/chapter3.log all these sub files under D:/test/chapters/ .
Sample code I have tried :
public class Example {
public Example() {
super();
}
public int plugin_execute() {
boolean foundstring=false;
try {
File dir = new File("D:/test/chapters");
String[] children = dir.list();
if (children == null) {
System.out.println("does not exist is not a directory");
} else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
if (filename !=null) {
foundstring = testString(filename, "tiger");
System.out.println("failed");
}
//Search for entry in file
if (!foundstring) {
return //failuremsg
} else {
System.out.println("failed");
return //succes
}
}
}
return 1;
} catch (Exception e) {
return //error mssg
}
}
private boolean teststring(String filePath, String str) {
BufferedReader br = null;
File file = new File(filePath);
boolean result = false;
if(!file.exists())
return false;
try {
br = new BufferedReader(new FileReader(filePath));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.contains(str)) {
result = true;
System.out.println(str);
System.out.println("Found entry ");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
It only returns the output of last file, means if it search success in last file it return success otherwise failed.
But I want success if string is found in first file. i.e chapter1 should return success, if not found in Chapter1 it should continue search in chapter2 ....
Please suggest how can I modify this code..

Problem: Simple mix-up with ! and true/false locations.
Solution: Change this
if (! foundString)
{
return // failuremsg
}
else
{
System.out.println("failed");
return // success
}
to
if (foundString)
{
// return success message
}
else
{
// return failure message
}
Another problem I believe I see in your code is that the line foundstring = findString(filename, "tiger"); calls the method findString, whereas the other method you posted in your code is testString. I assume this is a name mix up.

public void listFiles(Path dir , String text)
{
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir))
{
for (Path path : directoryStream)
{
if (Files.isRegularFile(path) && Files.isReadable(path))
{
//this.findString(path, text);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
private boolean findString(Path file, String text)
{
//Your implementation
return true;
}

Related

moving an ImapFolder to another Folder

In my little e-mail client I try to implement a feature to move an ImapFolder to another ImapFolder so that the first one is the secound one's subfolder.
Because I was not able to find any method which realizes that, I tried to implement the feature on my own like this:
public static boolean moveFolder(Folder move, Folder parent) {
Folder newFolder = FolderUtils.createFolder(parent, move.getName());
if(move == null || newFolder == null)
return false;
if(!(move instanceof IMAPFolder))
return false;
if(FolderUtils.openFolder(move))
try {
((IMAPFolder) move).moveMessages(move.getMessages(), newFolder);
FolderUtils.deleteFolder(move);
return true;
} catch (MessagingException e) {
e.printStackTrace();
}
return false;
}
public static boolean openFolder(Folder folder) {
if(folder == null)
return true;
if(!folder.getStore().isConnected())
return false;
if(!folder.isOpen()) {
try {
if(folder.getType() == Folder.HOLDS_FOLDERS)
return false;
} catch (MessagingException e1) {
}
try {
folder.open(Folder.READ_WRITE);
return true;
} catch (MessagingException e) {
return false;
}
}else
return true;
}
public static boolean deleteFolder(Folder folder) {
try {
if(folder != null){
if(folder.isOpen())
folder.close();
folder.delete(true);
return true;
}
} catch (Exception e) {
}
return false;
}
public static Folder createFolder(Folder parent, String name) {
try {
if(parent != null) {
Folder nF = parent.getFolder(name);
if(!nF.exists()) {
boolean result = nF.create(Folder.HOLDS_FOLDERS + Folder.HOLDS_MESSAGES);
if(result) {
nF.setSubscribed(true);
return nF;
}
}
}
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
My problem is that I allways get the following exception when I try to create a new Folder in a subfolder of my inbox:
javax.mail.MessagingException: Unsupported type;
nested exception is:
com.sun.mail.iap.ProtocolException: Unsupported type
at com.sun.mail.imap.IMAPFolder.doCommandIgnoreFailure(IMAPFolder.java:3898)
at com.sun.mail.imap.IMAPFolder.create(IMAPFolder.java:810)
at de.cpu.outlook.utils.FolderUtils.createFolder(FolderUtils.java:33)
at de.cpu.outlook.utils.FolderUtils.moveFolder(FolderUtils.java:63)
at de.cpu.outlook.gui.toolbars.utils.MoveFolderScreen$1$1.run(MoveFolderScreen.java:90)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: com.sun.mail.iap.ProtocolException: Unsupported type
at com.sun.mail.imap.IMAPFolder$6.doCommand(IMAPFolder.java:831)
at com.sun.mail.imap.IMAPFolder.doProtocolCommand(IMAPFolder.java:3921)
at com.sun.mail.imap.IMAPFolder.doCommandIgnoreFailure(IMAPFolder.java:3891)
... 5 more
Is there any way to fix this problem?

printing strings doubles and integers from a different file

So I'm new to java and I have to read strings, doubles, and integers from a file and print them out after. This is the error that java is throwing at me:
error: variable declaration not allowed here Scanner file = new
Scanner(line);
what am does it mean?
Scanner file = new Scanner(line);
Fails because a variable named file is already declared above ...
Scanner file = new Scanner(data);
Give one of the scanner variables a different name. There's some other problems with your code, but I assume this is a school assignment so only answered the question you asked.
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] splited = line.split(" ");
for (String st: splited) {
if(isInteger(st))
System.out.println("---int--->"+st);
else if(isDouble(st))
System.out.println("---dubl--->"+st);
else if (!st.isEmpty())
System.out.println("---String--->"+st);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static boolean isInteger(String st) {
try {
Integer.parseInt(st);
return true;
} catch (NumberFormatException e) {
return false;
}
}
static boolean isDouble(String str) {
try {
Float.parseFloat(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
This Maybe help you

JavaFX - HTMLElements are null when changing pages

When a user clicks on a link, I want to change the page and then load the relevant info.
However, the HTMLElement is always null.
The following is the code:
WebViewPanel.java
//to be used in JFX Thread
public void loadURLFX(final String url) {
if (Misc.stringHasContent(url)) {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
boolean invalidURL = false;
InputStream stream = null;
try {
URL urlObj = new URL(tmp);
stream = urlObj.openStream();
} catch (Exception e) {
invalidURL = true;
} finally {
try {
stream.close();
} catch (Exception ex) {
}
stream = null;
}
if (!invalidURL) {
engine.load(tmp);
} else {
//https://www.google.com.sg/search?q=searchTerm
engine.load("https://www.google.com.sg/search?q=" + url);
}
}
}
App.java
public void load(){
if(Platform.isFxApplicationThread()){
webViewPanel.loadURLFX(App.class.getResource("/hello.html").toExternalForm());
HTMLElement element = (HTMLElement) WebMisc.getHTMLElement(webViewPanel.getWebEngine(), "menu");
}
}
element is always null. What should I do to fix it?

busybox mv with whitespaces fails silently

I'm running a device with busybox.
Folder or files with no whitespaces moved correctly, but seems that folders with whitespaces don't move correctly
public static boolean mv(File source, File target) {
if (!source.exists() || !target.exists()) {
return false;
}
try {
StringBuilder command = new StringBuilder("mv -v ");
command.append('\"');
command.append(source.getCanonicalPath());
command.append('\"');
command.append(' ');
command.append('\"');
command.append(target.getCanonicalPath());
command.append('\"');
System.out.println(command.toString());
Process process = Runtime.getRuntime().exec(command.toString());
StringBuilder output = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
output.append(line);
}
System.out.println(output.toString());
return process.waitFor() == 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
The output is
mv -v "/storage/sdcard0/media/music/Progressive Death Metal" "/storage/sdcard0/Music"
No mv output, method just returns "false" (non-zero exit code).
And must I use canonical path, or is it okay to use absolute path and leave it to shell?
EDIT
I also came up that if the filename had quotes, the argument will be wrong, so I made a method adding escape characters
private static String getCommandLineString(String input) {
return input.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\'", "\\\'")
.replace("`", "\\`")
.replace(" ", "\\ ");
}
And now mv looks like this
public static boolean mv(File source, File target) {
if (!source.exists() || !target.exists()) {
return false;
}
try {
StringBuilder command = new StringBuilder("mv -v ");
command.append(getCommandLineString(source.getAbsolutePath()));
command.append(' ');
command.append(getCommandLineString(target.getAbsolutePath()));
System.out.println(command.toString());
Process process = Runtime.getRuntime().exec(command.toString());
StringBuilder output = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
output.append(line);
}
System.out.println(output.toString());
return process.waitFor() == 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
what I get is
mv -v /sdcard/media/music/Progressive\ Death\ Metal /sdcard/Music
But still I get silent non-zero exit code.
Finally got it working. Exec should ask for shell, while OutputStream should write commands.
private static boolean execute(boolean superuser, String command) {
DataOutputStream os = null;
try {
Process process = Runtime.getRuntime().exec(superuser ? "su" : "sh");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
return process.waitFor() == 0;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) { try { os.close(); } catch (Exception e) {} }
}
return false;
}
public static boolean mv(File source, File target) {
if (!source.exists() || !target.exists()) {
return false;
}
try {
StringBuilder command = new StringBuilder("mv ");
command.append(getCommandLineString(source.getAbsolutePath()));
command.append(' ');
command.append(getCommandLineString(target.getAbsolutePath()));
return execute(false, command.toString());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

Java continue executing loop if exception was throwd

Example: say I want to open a file. If I get a FileNotFoundException, I need to wait for some time and try again. How can I gracefully do that? Or do I need to use nested try/catch blocks?
Example :
public void openFile() {
File file = null;
try {
file = new <....>
} catch(FileNotFoundException e) {
}
return file;
}
You could use a do { ... } while (file == null) construct.
File file = null;
do {
try {
file = new <....>
} catch(FileNotFoundException e) {
// Wait for some time.
}
} while (file == null);
return file;
public File openFile() {
File file = null;
while (file == null) {
try {
file = new <....>
} catch(FileNotFoundException e) {
// Thread.sleep(waitingTime) or what you want to do
}
}
return file;
}
Note that this is a somewhat dangerous method, since there is no way to break out unless the file eventually appears. You could add a counter and give up after a certain number of tries, eg:
while (file == null) {
...
if (tries++ > MAX_TRIES) {
break;
}
}
public File openFile() {
File file = null;
while(true){
try {
file = new <....>
} catch(FileNotFoundException e) {
//wait for sometime
}
if(file!=null){
break;
}
}
return file;
}

Categories

Resources