There is a space between before and after = ...
( Backup = True )------ is a String to search(Even space is there between =)
File file = new File(
"D:\\Users\\kbaswa\\Desktop\\New folder\\MAINTENANCE-20150708.log.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.next();
lineNum++;
String name="Backup = True";
if (line.contains(name)) {
System.out.println("I found "+name+ " in file " +file.getName());
break;
}
else{
System.out.println("I didnt found it");
}
}
}
Scanner.next() returns the next complete token, so it will be returning something like Backup, then = next time round the loop, then true next time.
Use Scanner.nextLine() to get the entire line in one go.
scanner.nextLine() would solve your problem.
If you want to stick with scanner.next() you can define a delimiter: scanner.useDelimiter("\n") this reads the file until it hits the delimiter and starts the next loop from there.
You need to read the file line-by-line and search for your string in every line. The code should look something like:
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputString)) {
// a match!
System.out.println("Found " +inputString+ " in file ");
break;
}
}
Now to decide between Scanner or a BufferedReader to read the file, check this link. Also check this link for fast way of searching a string in file. Also keep in mind to close scanner once you are done.
Related
I'm creating a program, where i must read special text files. I have a problem with a reading text from specified word to another specified word(not including these words). Is using a scanner a good approach to this problem?
I mean something like that:
"text1
text2
text3
text4
text5"
And i want to get from it String with "text2 text3 text4".
I tried using useDelimeter but I can not figure out how to apply it to this case. I created a method that allows me to skip lines, but this is not a good solution in the long run and it will work for only one specified file.
Here is one of my methods I want to make it here
private String readFile3(File file) {
try {
Scanner sc = new Scanner(file);
//skipLine(sc, 8);
sc.useDelimiter("R");
String sentence = sc.next();
textAreaD.setText(sentence);
} catch (FileNotFoundException e) {
System.out.println("No file");
}
return null;
}
How about something like this:
private String readFile3(File file) {
try {
Scanner sc = new Scanner(file);
boolean save = false;
String sentence = "";
String temp = "";
while (sc.hasNextLine()) {
temp = sc.nextLine();
if (sentence.contains("text1")) {
if (!save) {
temp = sc.nextLine();
}
save = true;
}
if (sentence.contains("text5")) {
save = false;
}
if (save) {
sentence = sentence + temp;
}
}
// skipLine(sc, 8);
//sc.useDelimiter("R");
sentence = sentence.replaceAll("\\n", "");
textAreaD.setText(sentence);
} catch (FileNotFoundException e) {
System.out.println("No file");
}
return null;
}
Should read out all strings between "text1" and "text5". Maybe you have to do some more formatting and check if "text1" occurs more than one time, if you want to save that too, but i hope it helps you.
The goal of my program is to give the user the opportunity to add something in a new or old file.
Because of my code the user can add only one word to the file.
I wrote down where the problem is.
I do not know how to make the saving of the words in the file unlimited.
I tried with a for loop... Unfortunately it did not make any sense.
public class AddAndSave {
private static Scanner scanner = new Scanner(System.in);
private static Formatter formatter = null;
private static Scanner reader;
public static void main(String args[]) {
System.out.println("In which file do you want to add?");
String fileName = scanner.next();
File myFile = new File("C://Meine Dateien// " + fileName + ".txt");
if (myFile.exists() == true) {
try {
reader = new Scanner(myFile);
String fileContent = "";
while (reader.hasNext() == true) {
fileContent = fileContent + reader.next();
}
formatter = new Formatter(myFile);
formatter.format("%s", fileContent + " ");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
formatter = new Formatter(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("What do you want to add?");
String newInput = scanner.next();//hier is the problem
formatter.format("%s", newInput);
System.out.println();
System.out.println("Finish! Thank you for using our programm!");
formatter.close();
}
}
Your problem is the fact that you are utilizing the wrong Scanner method for retrieving String line data from both file and User.
Use the Scanner#nextLine() method instead of the Scanner#next() method and use it in conjunction with the Scanner#HasNextLine() method in your while loop condition (instead of the Scanner#hasNext() method):
String newInput = scanner.nextLine();
Use the Scanner#nextLine() method where you prompt for a file name and prompt for what to add to file!. Also use it within your while loop for reading the file (in conjuction with the Scanner#hasNextLine() method). Carefully read about the differences between all these methods!
Scanner#hasNext() and Scanner#next() methods are more geared towords Token (word) based situations (one word at a time) whereas the Scanner#hasNextLine() and Scanner#nextLine() methods are used for entire string lines. This is what I believe you really want.
Other Notes:
You may want to remove the white-space after your last forward slashes (//):
"C://Meine Dateien// " + fileName + ".txt";
unless of course you want t0 add a white-space at the beginning of every every name for every file created by your application.
When using boolean variables in conditions such as those in if statements, you can just use:
if (myFile.exists()) { // IF true
instead of:
if (myFile.exists() == true) { // IF true
and:
if (!myFile.exists()) { // IF false
instead of:
if (myFile.exists() == false) { // IF false
Either way works just fine but you will later find that the shorter way is less prone to errors due to typo's and I think it's easier to read but that's just my opinion.
Don't forget to close your file reader. Use Try With Resources to take care of this sort of thing for you with regards to both your reader and writer.
So, I'm trying to set up a simple config for a project. The goal here is to read certain values from a file and, if the file does not exist, to write said file. Currently, the creation of the file works fine, but my Scanner is acting a bit funny. When I reach the code
case "resolution": resolution = readConfig.next();
it makes the value of resolution "1024x768\nvsync" whereas it should only be "1024x768". If it were working as I planned, then the next value for
readingConfig = readConfig.next();
at the beginning of my while loop would be "vsync", which my switch statement would then catch and continue editing the values to those of the file.
Why is my Scanner picking up on the "\n" that is the 'enter' to the next line in the text document?
public static void main(String[] args) {
int musicVol = 0;
int soundVol = 0;
String resolution = null;
boolean vsync = false;
Scanner readConfig;
String readingConfig;
File configFile = new File(gameDir + "\\config.txt");
if (configFile.exists() != true) {
try {
configFile.createNewFile();
PrintWriter writer = new PrintWriter(gameDir + "\\config.txt");
writer.write("resolution = 1024x768 \n vsync = true \n music = 100 \n sound = 100");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
readConfig = new Scanner(configFile);
readConfig.useDelimiter(" = ");
while (readConfig.hasNext()) {
readingConfig = readConfig.next();
switch (readingConfig) {
case "resolution":
resolution = readConfig.next();
break;
case "vsync":
vsync = readConfig.nextBoolean();
break;
case "music":
musicVol = readConfig.nextInt();
break;
case "sound":
soundVol = readConfig.nextInt();
break;
}
}
readConfig.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Instead of using .hasNext and .next(), you will have to use .hasNextLine() and .nextLine(). I would write this as a comment, but do not have enought rep to comment yet.
You are using next() which will not delimit your lines, try using nextLine() instead:
String nextLine() Advances this scanner past the current line and
returns the input that was skipped.
I'd suggest not using the delimiter, and get the whole line instead as a string, and then split the string to the parts you want.
Something like
String nextLine = readConfig.nextLine();
String[] split = nextLine.split(" = ");
String resolution = split[1]; // just an example
...
Aha, solved!
What this does is pull the entire text file into a String (using Scanner.nextLine() removes the '\n') and then adds the " = " at the end of each line instead. Thus, when the Scanner runs back over the String for the switch, it will already be ignoring the " = " and pull the desired information from the String.
String config = "";
try {
readConfig = new Scanner(configFile);
while (readConfig.hasNext()) {
config += readConfig.nextLine() + " = ";
readConfig = new Scanner(config);
readConfig.useDelimiter(" = ");
I have a problem and don't know what to do. This method is supposed to read all the text in a .txt document. My problem is when the document contains more then one line of text and the program only read the last line. The program don't need to worry about signs like . , : or spaces, but it have to read all the letters. Can anybody help me?
example text
hello my name is
(returns the right result)
hello my
name is
(returns only name is)
private Scanner x;
String readFile(String fileName)
{
try {
x = new Scanner (new File(fileName + (".txt")));
}
catch (Exception e) {
System.out.println("cant open file");
}
while (x.hasNext()) {
read = x.next();
}
return read;
}
It's because when you use read = x.next(), the string in the read object is always being replaced by the text in the next line of the file. Use read += x.next() or read = read.concat(x.next()); instead.
You replace every read with every read(). Also, you didn't close() your Scanner. I would use a try-with-resources and something like,
String readFile(String fileName)
{
String read = "";
try (Scanner x = new Scanner (new File(fileName + (".txt")));) {
while (x.hasNextLine()) {
read += x.nextLine() + System.lineSeparator(); // <-- +=
}
} catch (Exception e) {
System.out.println("cant open file");
}
return read;
}
My java code takes almost 10-15minutes to run (Input file is 7200+ lines long list of query). How do I make it run in short time to get same results?
How do I make my code to search only for aA to zZ and 0 to 9??
If I don't do #2, some characters in my output are shown as "?". How do I solve this issue?
// no parameters are used in the main method
public static void main(String[] args) {
// assumes a text file named test.txt in a folder under the C:\file\test.txt
Scanner s = null;
BufferedWriter out = null;
try {
// create a scanner to read from the text file test.txt
FileInputStream fstream = new FileInputStream("C:\\user\\query.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// Write to the file
out = new BufferedWriter(new FileWriter("C:\\user\\outputquery.txt"));
// keep getting the next String from the text, separated by white space
// and print each token in a line in the output file
//while (s.hasNext()) {
// String token = s.next();
// System.out.println(token);
// out.write(token + "\r\n");
//}
String strLine="";
String str="";
while ((strLine = br.readLine()) != null) {
str+=strLine;
}
String st=str.replaceAll(" ", "");
char[]third =st.toCharArray();
System.out.println("Character Total");
for(int counter =0;counter<third.length;counter++){
//String ch= "a";
char ch= third[counter];
int count=0;
for ( int i=0; i<third.length; i++){
// if (ch=="a")
if (ch==third[i])
count++;
}
boolean flag=false;
for(int j=counter-1;j>=0;j--){
//if(ch=="b")
if(ch==third[j])
flag=true;
}
if(!flag){
System.out.println(ch+" "+count);
out.write(ch+" "+count);
}
}
// close the output file
out.close();
} catch (IOException e) {
// print any error messages
System.out.println(e.getMessage());
}
// optional to close the scanner here, the close can occur at the end of the code
finally {
if (s != null) {
// close the input file
s.close();
}
}
}
For something like this I would NOT recommend java though it entirely possible it is much easier with GAWK or something similar. GAWK also has java like syntax so its easy to pick up. You should check it out.
SO isn't really the place to ask such a broad how-do-I-do-this-question but I will refer you to the following page on regular expression and text match in Java. Also, check out the Javadocs for regexes.
If you follow that link you should get what you want, else you could post a more specific question back on SO.