First of all, I don't have any code to show yet, but the idea is that there is a text document that contains information, say... 'John Fitzgerald New York' on a single line, and I want to find that via .contains(), for example:
Scanner newScanner = new Scanner(inputFile);
String name = "Fitzgerald";
while(!newScanner.nextLine().contains(name)){
}
The idea being that I can then save the entire line as a variable. A search for Fitzgerald should allow me to save John Fitzgerald New York as a variable, in other words. Any ideas?
Scanner sc = new Scanner(new File("input.txt")); // Read from file
final String pattern = "Fitzgerald"
while( sc.hasNext() ){ // While you still have more data
String l = sc.next(); // Get the next token
if( l.contains(pattern) ){ // Check if it matches your pattern
System.out.println("Match Found");
}
}
This is how you would do it if you want to loop over the tokens. Alternatively, you can use the next(Pattern) method if you want to find more complex patterns.
For a text document, consider using a FileReader.
final String pattern = "Fitzgerald"
FileReader f = new FileReader(new File("input.txt"));
BufferedReader b = new BufferedReader(f);
String line;
while( (line=b.readLine()) != null ){
if(line.contains(pattern)){
doSomething(line);
}
}
Related
I need to search a String in a text file that the content in the text file will always be appended(in other method). For example String "abcdefg" need to be search exactly same in the file.
ArrayList<String> List = new ArrayList<String>();
FileReader filereader = new FileReader(file);
BufferedReader bufferreader = new BufferedReader(filereader);
String linetxt;
while((linetxt = bufferreader.readLine())!=null)
{
List.add(linetxt);
List.add("\r\n");
}
System.out.println("Please enter a string: ");
String usern = input.next();
System.out.println(List);
if ((List.contains(usern.substring(0,usern.length()))));
{
System.out.println("String existed.");
}
bufferreader.close();
The Test File current content (will always be added new content):
abcde12345
This is my code, but it occurs a problem that I will always get "String existed" no matter what I input(the String I input is not in the text file but it still printing that the String existed).
How can I modify my code to make that if my input is contained in the ArrayList, it will return "String existed"?
Is it any other ways to search a String in a text file(the content of text file will be appended in other method)?
Thanks.............. Hope everyone safe.
I am using #NameLookUp formula to retrieve internet address by giving a search key and it is working fine.But now i want to retrive not only the internet address but also some other properties like FirstName and LastName.
Here is the formula i am using to #Namelookup internet address by giving search string.
Vector vec=m_session.evaluate("#NameLookup([NoUpdate];\""+ userName + "\"; \"InternetAddress\")");
//username is the String variable(Search Criteria)
Can anyone please help how to retrieve multiple properties(like firstName and lastName along with InternetAddress) by evaluate the formula only once. If it cant be done using #Namelookup is there any other way..?
This is a typical example when using evaluate() to call a Formula is not a good idea.
What you want to do is to get the NotesDocument class and read values from it.
Something like this (disclaimer, I am not a Java developer):
// Open Domino Directory on specified server
Database db = session.getDatabase("YourServer/Domain", "names.nsf");
// Get a view with user name is sorted first column
View view = db.getView("($Users)");
// Get the person document for specified user
Document doc = view.getDocumentByKey(userName, true);
if (doc != null) {
// Get text values from Notes document
String emailAddress = doc.getItemValueString("InternetAddress");
String officePhone = doc.getItemValueString("OfficeNumber");
String officeAddress = doc.getItemValueString("OfficeStreetAddress");
}
I believe this would be faster than multiple lookups using evaluate(), and you also have the added benefit of full error handling, and all being native code.
#NameLookup only returns the value of one item per call.
Assuming your goal is to only have one Evaluate statement, you could chain the calls together and return an array of values in a certain order:
Vector vec=m_session.evaluate("FirstName := #NameLookup([NoUpdate];\""+ userName + "\"; \"FirstName\"); LastName:= #NameLookup([NoUpdate];\""+ userName + "\"; \"LastName\"); InternetAddress :=#NameLookup([NoUpdate];\""+ userName + "\"; \"InternetAddress\"); FirstName:LastName:InternetAddress");
Or possibly:
String firstName = m_session.evaluate("#NameLookup([NoUpdate];\""+ userName + "\"; \"FirstName\")");
String lastName = m_session.evaluate("#NameLookup([NoUpdate];\""+ userName + "\"; \"LastName\")");
String internetAddress = m_session.evaluate("#NameLookup([NoUpdate];\""+ userName + "\"; \"InternetAddress\")");
And then add those three strings in any order into your Vector.
Another approach is to use the DirectoryNavigator class. I believe it's been available since Notes/Domino 8.5 (perhaps even before that). DirectoryNavigator uses some of the same core logic as #NameLookup, so it should perform well.
Here's some sample code. I haven't tested this exact code, but I adapted it from production code that does a similar lookup:
String firstName = null;
String lastName = null;
String inetAddress = null;
Vector<String> lookupItems = new Vector<String>();
lookupItems.addElement("FirstName");
lookupItems.addElement("LastName");
lookupItems.addElement("InternetAddress");
Vector<String> vName = new Vector<String>();
vName.addElement(userName);
Directory dir = session.getDirectory();
DirectoryNavigator dirNav = dir.lookupNames("($Users)", vName, lookupItems, true);
if( dirNav != null && dirNav.getCurrentMatches() != 0 ) {
// Digest the results of the lookup
Vector<String> value = null;
value = dirNav.getFirstItemValue();
firstName = value.elementAt(0);
value = dirNav.getNextItemValue();
lastName = value.elementAt(0);
value = dirNav.getNextItemValue();
inetAddress = value.elementAt(0);
}
I am writing a text file and each time i write i want to clear the text file.
try
{
string fileName = "Profile//" + comboboxSelectProfile.SelectedItem.ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(("Default//DefaultProfile.txt").ToString(), true))
{
sw.WriteLine(fileName);
MessageBox.Show("Default is set!");
}
DefaultFileName = "Default//DefaultProfile.txt";
}
catch
{
}
How do I do this? I want to remove all previous content from DefaultProfile.txt.
I actually have to know the method or way (just a name could be) to remove all content from the text file.
You could just write an empty string to the existing file:
File.WriteAllText(#"Default\DefaultProfile.txt", string.Empty);
Or change the second parameter in the StreamWriter constructor to false to replace the file contents instead of appending to the file.
You can look at the Truncate method
FileInfo fi = new FileInfo(#"Default\DefaultProfile.txt");
using(TextWriter txtWriter = new StreamWriter(fi.Open(FileMode.Truncate)))
{
txtWriter.Write("Write your line or content here");
}
The most straightforward and efficient technique is to use the StreamWriter constructor's boolean parameter. When it's set to false it overwrites the file with the current operation. For instance, I had to save output of a mathematical operation to a text file. Each time I wanted ONLY the current answer in the text file. So, on the first StreamWriter operation, I set the boolean value to false and the subsequent calls had the bool val set to true. The result is that for each new operation, the previous answer is overwritten and only the new answer is displayed.
int div = num1 / denominator;
int mod = num1 % denominator;
Console.Write(div);
using (StreamWriter writer = new StreamWriter(FILE_NAME, false ))
{
writer.Write(div);
}
Console.Write(".");
using (StreamWriter writer = new StreamWriter(FILE_NAME, true))
{
writer.Write(".");
}
You can use FileMode.Truncate. Code will look like
FileStream fs = new
FileStream(filePath, FileMode.Truncate, FileAccess.Write )
{
fs.Close();
}
System.IO.File.Delete, or one of the System.IO.FileStream constructor overloads specifying FileMode.Create
Simply change the second parameter from true to false in the contructor of StreamWriter.
using (StreamWriter sw = new StreamWriter(("Default//DefaultProfile.txt").ToString(), **false**))
See StreamWriter Contructor
I have a folder with .pdf files. In the names of most files I want to replace specific string with another string.
Here's what I've written.
private void btnGetFiles_Click(object sender, EventArgs e)
{
string dir = tbGetFIles.Text;
List<string> FileNames = new List<string>();
DirectoryInfo DirInfo = new DirectoryInfo(dir);
foreach (FileInfo File in DirInfo.GetFiles())
{
FileNames.Add(File.Name);
}
lbFileNames.DataSource = FileNames;
}
Here I extract all file names in List Box.
private void btnReplace_Click(object sender, EventArgs e)
{
string strReplace = tbReplace.Text; // The existing string
string strWith = tbWith.Text; // The new string
string dir = tbGetFIles.Text;
DirectoryInfo DirInfo = new DirectoryInfo(dir);
FileInfo[] names = DirInfo.GetFiles();
foreach (FileInfo f in names)
{
if(f.Name.Contains(strReplace))
{
f.Name.Replace(strReplace, strWith);
}
}
And here I want to do the replacing, but something is going wrong. What?
It sounds like you want to change the name of the file on disk. If so then you need to use the File.Move API vs. changing the actual string which is the file name.
One other mistake you are making is the Replace call itself. A string in .Net is immutable and hence all of the mutating APIs like Replace return a new string vs. changing the old one in place. To see the change you need to assign the new value back to a variable
string newName = f.Name.Replace(strReplace, strWith);
File.Move(f.Name, newName);
f.Name is a read-only property. f.Name.Replace(..) simply returns a new string with the filename you want, but never actually changes the file.
I suggest something along the following, though I haven't tested it:
File.Move(f.Name, f.Name.Replace(strReplace, strWith));
Replace return another string, it doesn't change the original string.
So you need to write
string newName = f.Name.Replace(strReplace, strWith);
of course this doesn't change the name of the file on disk.
If that was your intention then you should look at
File.Move(f.Name, newName);
also keep in mind that File.Move will fail with an exception if the destination file exists.
See here for an example
At a first glance, seems like you're not reassigning the replaced string to your f.Name variable. Try this:
string NewFileName = f.Name.Replace(strReplace, strWith);
File.Copy(f.Name, NewFileName);
File.Delete(f.Name);
When you call string.Replace this doesn't alter your existing string. Instead it is returning a new string.
You need to change your code to something like this:
if(f.Name.Contains(strReplace))
{
string newFileName = f.Name.Replace(strReplace, strWith);
//and work here with your new string
}
I've written a simple login system using a JPQL query, which always returns no result:
public boolean check(String name, String password) {
final String qstring="SELECT e FROM Muser e WHERE e.name = '"+name+"'";
Muser user;
try{
user = em.createQuery(qstring, Muser.class).getSingleResult();
}
catch(NoResultException e){
return false;
}
return password.equals(user.getPassword());
}
When I changed it to a native query:
user = (Muser) em.createNativeQuery(qstring, Muser.class).getSingleResult();
or an int expression:
final String qstring="SELECT e FROM Muser e WHERE e.id = "+id;
It goes all right. What's the problem? Thanks a million!
It might be a problem with string comparison in your JPA provider. Do you test it on the case-sensitive data?
You could also try (and it's the preferred way) using parameters instead of crafting your statement by hand. It's not only safer (prevents SQL injection) but also faster: not only for Java (you don't concatenate Strings) but also for the DB (the query can be prepared once for all executions). It might be something like this:
final String qstring = "SELECT e FROM Muser e WHERE e.name = :name";
TypedQuery<Muser> query = em.createQuery(qstring, Muser.class);
query.setParameter("name", name);
user = query.getSingleResult();
I think problem is because of String comparison.My solution to this problem is:
using lowercase for comparison.
final String qstring = "SELECT e FROM Muser e WHERE LOWER(e.name) = :name";
TypedQuery<Muser> query = em.createQuery(qstring, Muser.class);
query.setParameter("name", name.toLowerCase());
user = query.getSingleResult();