I need an equivalent behaviour in java for this command in Unix cli:
ls /data/archive/users/*/*.xml
Which outputs me:
/data/archive/users/2012/user1.xml
/data/archive/users/2013/user2.xml
Is there a simple equivalent implementation for Java 6?
Get user input using java.util.Scanner and use java.io.File.listFiles(FilenameFilter) method to get the list of files in the folder with specific filter.
Yes, there is, and it's called the list method of the File class. See it's Javadoc for details.
I forget where this came from but this should be a good start. There are many more available via Google.
public class RegexFilenameFilter implements FilenameFilter {
/**
* Only file name that match this regex are accepted by this filter
*/
String regex = null; // setting the filter regex to null causes any name to be accepted (same as ".*")
public RegexFilenameFilter() {
}
public RegexFilenameFilter(String filter) {
setWildcard(filter);
}
/**
* Set the filter from a wildcard expression as known from the windows command line
* ("?" = "any character", "*" = zero or more occurances of any character")
*
* #param sWild the wildcard pattern
*
* #return this
*/
public RegexFilenameFilter setWildcard(String sWild) {
regex = wildcardToRegex(sWild);
// throw PatternSyntaxException if the pattern is not valid
// this should never happen if wildcardToRegex works as intended,
// so thiw method does not declare PatternSyntaxException to be thrown
Pattern.compile(regex);
return this;
}
/**
* Set the regular expression of the filter
*
* #param regex the regular expression of the filter
*
* #return this
*/
public RegexFilenameFilter setRegex(String regex) throws java.util.regex.PatternSyntaxException {
this.regex = regex;
// throw PatternSyntaxException if the pattern is not valid
Pattern.compile(regex);
return this;
}
/**
* Tests if a specified file should be included in a file list.
*
* #param dir the directory in which the file was found.
*
* #param name the name of the file.
*
* #return true if and only if the name should be included in the file list; false otherwise.
*/
public boolean accept(File dir, String name) {
boolean bAccept = false;
if (regex == null) {
bAccept = true;
} else {
bAccept = name.toLowerCase().matches(regex);
}
return bAccept;
}
/**
* Converts a windows wildcard pattern to a regex pattern
*
* #param wild - Wildcard patter containing * and ?
*
* #return - a regex pattern that is equivalent to the windows wildcard pattern
*/
private static String wildcardToRegex(String wild) {
if (wild == null) {
return null;
}
StringBuilder buffer = new StringBuilder();
char[] chars = wild.toLowerCase().toCharArray();
for (int i = 0; i < chars.length; ++i) {
if (chars[i] == '*') {
buffer.append(".*");
} else if (chars[i] == '?') {
buffer.append('.');
} else if (chars[i] == ';') {
buffer.append('|');
} else if ("+()^$.{}[]|\\".indexOf(chars[i]) != -1) {
buffer.append('\\').append(chars[i]); // prefix all metacharacters with backslash
} else {
buffer.append(chars[i]);
}
}
return buffer.toString();
}
}
Here is the code I used, it works with relative and absolute paths:
DirectoryScanner scanner = new DirectoryScanner();
if (!inputPath.startsWith("/") || inputPath.startsWith(".")) {
scanner.setBasedir(".");
}
scanner.setIncludes(new String[]{inputPath});
scanner.setCaseSensitive(false);
scanner.scan();
String[] foundFiles = scanner.getIncludedFiles();
(DirectoryScanner from org.apache.tools.ant)
Related
I am using change stream to see the changes in mongodb. I retrieve the document in the below format, now how to parse in strings. I need the value of $oid and name
Full document is
{"_id": {"$oid": "5c60f87a9ea5deac53457e9c"}, "name": "freddy"}
I am using Java code
MongoCursor<ChangeStreamDocument<BasicDBObject>> cursor1 = collection.watch().iterator();
System.out.println("Connection Completely Established 4");
for(int i = 1; i <= 200; i++)
{
ChangeStreamDocument<BasicDBObject> next1 = cursor1.next();
System.out.println("Operation Type is " + next1.getOperationType());
System.out.println("Database Name is" + next1.getDatabaseName());
System.out.println("Full Document is " + next1.getFullDocument());
}
If you know the format of the document string then you can use a method to acquire the data needed. The getBetween() method below will retrieve the information you want from your provided document string, here is how it might be used to achieve this:
String docString = "Full Document is {\"_id\": {\"$oid\": \"5c60f87a9ea5deac53457e9c\"}, \"name\": \"freddy\"}";
String oid = getBetween(docString, "$oid\": \"", "\"}")[0];
String name = getBetween(docString, "name\": \"", "\"}")[0];
System.out.println(oid);
System.out.println(name);
The Console Window will display:
5c60f87a9ea5deac53457e9c
freddy
Here is the getBetween() method:
/**
* Retrieves any string data located between the supplied string leftString
* parameter and the supplied string rightString parameter.<br><br>
* <p>
* <p>
* This method will return all instances of a substring located between the
* supplied Left String and the supplied Right String which may be found
* within the supplied Input String.<br>
*
* #param inputString (String) The string to look for substring(s) in.
*
* #param leftString (String) What may be to the Left side of the substring
* we want within the main input string. Sometimes the
* substring you want may be contained at the very
* beginning of a string and therefore there is no
* Left-String available. In this case you would simply
* pass a Null String ("") to this parameter which
* basically informs the method of this fact. Null can
* not be supplied and will ultimately generate a
* NullPointerException.
*
* #param rightString (String) What may be to the Right side of the
* substring we want within the main input string.
* Sometimes the substring you want may be contained at
* the very end of a string and therefore there is no
* Right-String available. In this case you would simply
* pass a Null String ("") to this parameter which
* basically informs the method of this fact. Null can
* not be supplied and will ultimately generate a
* NullPointerException.
*
* #param options (Optional - Boolean - 2 Parameters):<pre>
*
* ignoreLetterCase - Default is false. This option works against the
* string supplied within the leftString parameter
* and the string supplied within the rightString
* parameter. If set to true then letter case is
* ignored when searching for strings supplied in
* these two parameters. If left at default false
* then letter case is not ignored.
*
* trimFound - Default is true. By default this method will trim
* off leading and trailing white-spaces from found
* sub-string items. General sentences which obviously
* contain spaces will almost always give you a white-
* space within an extracted sub-string. By setting
* this parameter to false, leading and trailing white-
* spaces are not trimmed off before they are placed
* into the returned Array.</pre>
*
* #return (1D String Array) Returns a Single Dimensional String Array
* containing all the sub-strings found within the supplied Input
* String which are between the supplied Left String and supplied
* Right String.
*/
public String[] getBetween(String inputString, String leftString, String rightString, boolean... options) {
// Return nothing if nothing was supplied.
if (inputString.equals("") || (leftString.equals("") && rightString.equals(""))) {
return null;
}
// Prepare optional parameters if any supplied.
// If none supplied then use Defaults...
boolean ignoreCase = false; // Default.
boolean trimFound = true; // Default.
if (options.length > 0) {
if (options.length >= 1) {
ignoreCase = options[0];
}
if (options.length >= 2) {
trimFound = options[1];
}
}
// Remove any ASCII control characters from the
// supplied string (if they exist).
String modString = inputString.replaceAll("\\p{Cntrl}", "");
// Establish a List String Array Object to hold
// our found substrings between the supplied Left
// String and supplied Right String.
List<String> list = new ArrayList<>();
// Use Pattern Matching to locate our possible
// substrings within the supplied Input String.
String regEx = Pattern.quote(leftString)
+ (!rightString.equals("") ? "(.*?)" : "(.*)?")
+ Pattern.quote(rightString);
if (ignoreCase) {
regEx = "(?i)" + regEx;
}
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(modString);
while (matcher.find()) {
// Add the found substrings into the List.
String found = matcher.group(1);
if (trimFound) {
found = found.trim();
}
list.add(found);
}
return list.toArray(new String[0]);
}
I'm trying to find the strings in a TreeSet<String> that start with a given prefix. I found a previous question asking for the same thing — Searching for a record in a TreeSet on the fly — but the answer given there doesn't work for me, because it assumes that the strings don't include Character.MAX_VALUE, and mine can.
(The answer there is to use treeSet.subSet(prefix, prefix + Character.MAX_VALUE), which gives all strings between prefix (inclusive) and prefix + Character.MAX_VALUE (exclusive), which comes out to all strings that start with prefix except those that start with prefix + Character.MAX_VALUE. But in my case I need to find all strings that start with prefix, including those that start with prefix + Character.MAX_VALUE.)
How can I do this?
To start with, I suggest re-examining your requirements. Character.MAX_VALUE is U+FFFF, which is not a valid Unicode character and never will be; so I can't think of a good reason why you would need to support it.
But if there's a good reason for that requirement, then — you need to "increment" your prefix to compute the least string that's greater than all strings starting with your prefix. For example, given "city", you need "citz". You can do that as follows:
/**
* #param prefix
* #return The least string that's greater than all strings starting with
* prefix, if one exists. Otherwise, returns Optional.empty().
* (Specifically, returns Optional.empty() if the prefix is the
* empty string, or is just a sequence of Character.MAX_VALUE-s.)
*/
private static Optional<String> incrementPrefix(final String prefix) {
final StringBuilder sb = new StringBuilder(prefix);
// remove any trailing occurrences of Character.MAX_VALUE:
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == Character.MAX_VALUE) {
sb.setLength(sb.length() - 1);
}
// if the prefix is empty, then there's no upper bound:
if (sb.length() == 0) {
return Optional.empty();
}
// otherwise, increment the last character and return the result:
sb.setCharAt(sb.length() - 1, (char) (sb.charAt(sb.length() - 1) + 1));
return Optional.of(sb.toString());
}
To use it, you need to use subSet when the above method returns a string, and tailSet when it returns nothing:
/**
* #param allElements - a SortedSet of strings. This set must use the
* natural string ordering; otherwise this method
* may not behave as intended.
* #param prefix
* #return The subset of allElements containing the strings that start
* with prefix.
*/
private static SortedSet<String> getElementsWithPrefix(
final SortedSet<String> allElements, final String prefix) {
final Optional<String> endpoint = incrementPrefix(prefix);
if (endpoint.isPresent()) {
return allElements.subSet(prefix, endpoint.get());
} else {
return allElements.tailSet(prefix);
}
}
See it in action at: http://ideone.com/YvO4b3.
If anybody is looking for a shorter version of ruakh's answer:
First element is actually set.ceiling(prefix),and last - you have to increment the prefix and use set.floor(next_prefix)
public NavigableSet<String> subSetWithPrefix(NavigableSet<String> set, String prefix) {
String first = set.ceiling(prefix);
char[] chars = prefix.toCharArray();
if(chars.length>0)
chars[chars.length-1] = (char) (chars[chars.length-1]+1);
String last = set.floor(new String(chars));
if(first==null || last==null || last.compareTo(first)<0)
return new TreeSet<>();
return set.subSet(first, true, last, true);
}
According to the rubric, for this program we are to use "two stacks to evaluate an infix arithmetic expression from an InputStream. It should not create a full postfix expression along the way; it should convert and evaluate in a pipelined fashion, in a single pass."
package cs445.a2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class InfixExpressionEvaluator {
// Tokenizer to break up our input into tokens
StreamTokenizer tokenizer;
// Stacks for operators (for converting to postfix) and operands (for
// evaluating)
StackInterface<Character> operatorStack;
StackInterface<Double> operandStack;
/**
* Initializes the evaluator to read an infix expression from an input
* stream.
* #param input the input stream from which to read the expression
*/
public InfixExpressionEvaluator(InputStream input) {
// Initialize the tokenizer to read from the given InputStream
tokenizer = new StreamTokenizer(new BufferedReader(
new InputStreamReader(input)));
// StreamTokenizer likes to consider - and / to have special meaning.
// Tell it that these are regular characters, so that they can be parsed
// as operators
tokenizer.ordinaryChar('-');
tokenizer.ordinaryChar('/');
// Allow the tokenizer to recognize end-of-line, which marks the end of
// the expression
tokenizer.eolIsSignificant(true);
// Initialize the stacks
operatorStack = new ArrayStack<Character>();
operandStack = new ArrayStack<Double>();
}
/**
* Parses and evaluates the expression read from the provided input stream,
* then returns the resulting value
* #return the value of the infix expression that was parsed
*/
public Double evaluate() throws ExpressionError {
// Get the first token. If an IO exception occurs, replace it with a
// runtime exception, causing an immediate crash.
try {
tokenizer.nextToken();
} catch (IOException e) {
throw new RuntimeException(e);
}
// Continue processing tokens until we find end-of-line
while (tokenizer.ttype != StreamTokenizer.TT_EOL) {
// Consider possible token types
switch (tokenizer.ttype) {
case StreamTokenizer.TT_NUMBER:
// If the token is a number, process it as a double-valued
// operand
processOperand((double)tokenizer.nval);
break;
case '+':
case '-':
case '*':
case '/':
case '^':
// If the token is any of the above characters, process it
// is an operator
processOperator((char)tokenizer.ttype);
break;
case '(':
case '[':
// If the token is open bracket, process it as such. Forms
// of bracket are interchangeable but must nest properly.
processOpenBracket((char)tokenizer.ttype);
break;
case ')':
case ']':
// If the token is close bracket, process it as such. Forms
// of bracket are interchangeable but must nest properly.
processCloseBracket((char)tokenizer.ttype);
break;
case StreamTokenizer.TT_WORD:
// If the token is a "word", throw an expression error
throw new ExpressionError("Unrecognized token: " +
tokenizer.sval);
default:
// If the token is any other type or value, throw an
// expression error
throw new ExpressionError("Unrecognized token: " +
String.valueOf((char)tokenizer.ttype));
}
// Read the next token, again converting any potential IO exception
try {
tokenizer.nextToken();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
// Almost done now, but we may have to process remaining operators in
// the operators stack
processRemainingOperators();
// Return the result of the evaluation
// TODO: Fix this return statement
return null;
}
/**
* This method is called when the evaluator encounters an operand. It
* manipulates operatorStack and/or operandStack to process the operand
* according to the Infix-to-Postfix and Postfix-evaluation algorithms.
* #param operand the operand token that was encountered
*/
void processOperand(double operand) {
// TODO: Complete this method
}
/**
* This method is called when the evaluator encounters an operator. It
* manipulates operatorStack and/or operandStack to process the operator
* according to the Infix-to-Postfix and Postfix-evaluation algorithms.
* #param operator the operator token that was encountered
*/
void processOperator(char operator) {
// TODO: Complete this method
}
/**
* This method is called when the evaluator encounters an open bracket. It
* manipulates operatorStack and/or operandStack to process the open bracket
* according to the Infix-to-Postfix and Postfix-evaluation algorithms.
* #param openBracket the open bracket token that was encountered
*/
void processOpenBracket(char openBracket) {
// TODO: Complete this method
}
/**
* This method is called when the evaluator encounters a close bracket. It
* manipulates operatorStack and/or operandStack to process the close
* bracket according to the Infix-to-Postfix and Postfix-evaluation
* algorithms.
* #param closeBracket the close bracket token that was encountered
*/
void processCloseBracket(char closeBracket) {
// TODO: Complete this method
}
/**
* This method is called when the evaluator encounters the end of an
* expression. It manipulates operatorStack and/or operandStack to process
* the operators that remain on the stack, according to the Infix-to-Postfix
* and Postfix-evaluation algorithms.
*/
void processRemainingOperators() {
// TODO: Complete this method
}
/**
* Creates an InfixExpressionEvaluator object to read from System.in, then
* evaluates its input and prints the result.
* #param args not used
*/
public static void main(String[] args) {
System.out.println("Infix expression:");
InfixExpressionEvaluator evaluator =
new InfixExpressionEvaluator(System.in);
Double value = null;
try {
value = evaluator.evaluate();
} catch (ExpressionError e) {
System.out.println("ExpressionError: " + e.getMessage());
}
if (value != null) {
System.out.println(value);
} else {
System.out.println("Evaluator returned null");
}
}
}
I'm at a lost on how to implement the "void processOperand(double operand)" method(only need to worry about this method for now). I do understand how to convert Infix-to-Postfix using numbers/variables but I don't understand how to do the coding part. Could anybody give me a hint on how to start this method? I have also included the StackInterface class which has all of the push,pop,peek,etc. methods.
package cs445.a2;
import java.util.EmptyStackException;
public interface StackInterface<E> {
/** Adds a new entry to the top of this stack.
* #param newEntry An object to be added to the stack */
public void push(E newEntry);
/** Removes and returns this stack's top entry.
* #return The object at the top of the stack.
* #throws EmptyStackException if the stack is empty. */
public E pop() throws EmptyStackException;
/** Retrieves this stack's top entry.
* #return The object at the top of the stack.
* #throws EmptyStackException if the stack is empty. */
public E peek() throws EmptyStackException;
/** Detects whether this stack is empty.
* #return True if the stack is empty. */
public boolean isEmpty();
/** Removes all entries from this stack. */
public void clear();
}
I would like to know how to print a particular index to Upper and Lower Case?
I don't know for the particular index to change?
For single index this is the code...
public class UpperAndLowerCase {
public static void main(String[] args) {
String input="India";
int index=input.indexOf('i');
String result=input.substring(0,index)+input.substring(index,index+1).toUpperCase()+input.substring(index+1);
System.out.println(result);
}
}
The output of this program is : IndIa
But I want the output like this: indIa (In a given input String, first 'I' to 'i' and next 'i' to 'I')
Below is generic implementation which will give you expected result.
public static void main(String[] args) {
String input = "India";
String newInput = replaceCharacterToUpperCase(input, 'i', true);
System.out.println(newInput);
String newInput2 = replaceCharacterToLowerCase(newInput, 'I', false);
System.out.println(newInput2);
}
/**
*
* #param input: Input string to work on.
* #param c: Character to convert case
* #param isAllOccurance: Whether to replace all occurrence or single occurrence
* #return
*/
private static String replaceCharacterToUpperCase(String input, char c, boolean isAllOccurance) {
int index = input.indexOf(c);
if(isAllOccurance){
return input.replace(input.charAt(index), Character.toUpperCase(input.charAt(index)));
} else{
return input.replaceFirst(Character.toString(input.charAt(index)), Character.toString(Character.toUpperCase(input.charAt(index))));
}
}
/**
*
* #param input: Input string to work on.
* #param c: Character to convert case
* #param isAllOccurance: Whether to replace all occurrence or single occurrence
* #return
*/
private static String replaceCharacterToLowerCase(String input, char c, boolean isAllOccurance) {
int index = input.indexOf(c);
if(isAllOccurance){
return input.replace(input.charAt(index), Character.toLowerCase(input.charAt(index)));
} else{
return input.replaceFirst(Character.toString(input.charAt(index)), Character.toString(Character.toLowerCase(input.charAt(index))));
}
}
Disclaimer: This is not tested exhaustively to cover all possible requirements or scenarios anybody can have, so on basis of your special requirement you may need to tweak the things a bit.
Basically to replace single character in a String, you can use below code:
int index=input.indexOf('i');
String newInput = input.replace(input.charAt(index), Character.toUpperCase(input.charAt(index)));
There are many methods in String class which lets you do replacements, based on your requirement like whether character or string, first occurrenceor all occurrence. Methods like:
replaceFirst(String regex, String replacement)
replaceAll(String regex, String replacement)
replace(CharSequence target, CharSequence replacement)
String selectedVal = "";
for (SelectItem item : filterItems) {
selectedVal = item.getValue().toString();
break;
}
I am getting selectedVal=" " how to check this empty space in java.
I tried with if(!selectedVal.equals("") and if(!selectedVal.isEmpty()) but condition getting true.How to check more than one empty space ?
You can trim() your string before checking with isEmpty()
boolean isEmpty = myString.trim().isEmpty();
Beware of isEmpty(), it's only available since Java SE 6
Resources :
javadoc - String.trim()
javadoc - String.isEmpty()
I use this all the time:
public static boolean isBlank(String s)
{
return (s == null) || (s.trim().length() == 0);
}
Returns true on null, empty string, or whitespace only.
For such a simple test, using an external library is not a good idea, but if you need String manipulation (left and right padding, etc.), you can go for Apache commons lang and the
StringUtils.isEmpty() method.
More recently, you can use the Google Guava library and the class Strings. This library has a lot of usefull util methods (null handling, etc.). Once again, use this library only if you have others needs than checking empty strings.
boolean isEmpty = myString.toString().trim().isEmpty()
I use a routine similar to what Grodriguez posted. It ends up in a util/BagOTricks.java file in every project. My routine does a similar check and returns a null as a space, or the trimmed input string.
I am not a java programmer, but with regex, \s means white space.
This link might also be useful:
/**
* Helper function for making null strings safe for comparisons, etc.
*
* #return (s == null) ? "" : s;
*/
public static String makeSafe(String s) {
return (s == null) ? "" : s;
}
/**
* Helper function for null, empty, and whitespace string testing.
*
* #return true if s == null or s.equals("") or s contains only whitespace
* characters.
*/
public static boolean isEmptyOrWhitespace(String s) {
s = makeSafe(s);
for (int i = 0, n = s.length(); i < n; i++) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
You can use this method:
public boolean isNullOrEmpty(String s) {
return s == null || s.trim().isEmpty();
}
Method returns true when passed string is null or empty / only contains blank spaces.
Using the Apache Commons Lang library, you can use StringUtils.isEmpty() to check if a String is empty ("") or null, and StringUtils.isBlank() to check if a String is whitespace, empty ("") or null.
Note the differences:
isEmpty()
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
isBlank()
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false