I was just wondering if there is a way to loop through a text file until a particular string is found.
For example, say you have a text file with the following in it:
banana
apple
grapes
melon
orange
cherries
strawberry chocolate vanilla
I basically want to write a program that loops through the input file until it gets to a particular string the user specifies and then stores the next line in an array list. So, basically say if I imputed cherries I want it to store strawberry, chocolate, vanilla in an array list. For the life of me I cannot figure out how to do this though, so anything would be appreciated. What I have so far is below.
public static void main(String[] args) throws IOException {
String line;
ArrayList<String> names = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String input = in.next();
FileReader file = new FileReader(input);
BufferedReader reader = new BufferedReader(file);
System.out.print("What fruit do you want: ");
String fruit = in.next();
line = reader.readLine();
while ((line != null)) {
if(line.equals(fruit){
}
}
Just loop through the input until the searched line is encountered and store every line found afterwards in the list.
String line;
while((line = reader.readLine()) != null)
if(line.equals(fruit))
break;
ArrayList<String> lines = new ArrayList<>();
while((line = reader.readLine()) != null)
lines.add(line);
if I understand your question correctly, I have an idea that you can start from
Scanner scanner = new Scanner(file);
List<String> list = new ArrayList<String>();
while (scanner.hasNextLine()) { // read the entire file into list but it consumes time especially if the file is big (not perfect choice)
list.add(scanner.nextLine());
}
now what you can do
// add boolean to announce the occurrance of the word
boolean found = false;
for(String word: list){ // then you have a greater control over it to search
if(word.equals(fruit)){
found = true;
}
if (found) {
// start taking the rest of the array into a new array or whatever you want to do
}
}
You could use a boolean to indicate when the value is found and when it is true you can add the line in the List :
boolean isFound = false;
String line;
while ((line=reader.readLine())!= null) {
if(!isFound && line.equals(fruit){
isFound = true;
}
else if (isFound){
names.add(line);
}
}
Create flag isFound. Set it to true when you find the string.
It will then process on the next loop and set to false like so.
bool isFound=false;
while ((line != null)) {
if(isFound==true){
names.add(string)
isFound=false;
}
if(line.equals(fruit){
isFound=true;
}
}
check it out:
public static void main(String[] args) throws IOException {
String line;
List<String> names = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String input = in.next();
FileReader file = new FileReader(input);
BufferedReader reader = new BufferedReader(file);
System.out.print("What fruit do you want: ");
String fruit = in.next();
boolean found=false;
while ((line = reader.readLine()) != null){
if (line.equals(fruit) || found) {
names.add(line);
found=true;
}
}
}
Related
I have a text file list of thousands of String (3272) and I want to put them each into a slot of an Array so that I can use them to be sorted out. I have the sorting part done I just need help putting each line of word into an array. This is what I have tried but it only prints the last item from the text file.
public static void main(String[] args) throws IOException
{
FileReader fileText = new FileReader("test.txt");
BufferedReader scan = new BufferedReader (fileText);
String line;
String[] word = new String[3272];
Comparator<String> com = new ComImpl();
while((line = scan.readLine()) != null)
{
for(int i = 0; i < word.length; i++)
{
word[i] = line;
}
}
Arrays.parallelSort(word, com);
for(String i: word)
{
System.out.println(i);
}
}
Each time you read a line, you assign it to all of the elements of word. This is why word only ends up with the last line of the file.
Replace the while loop with the following code.
int next = 0;
while ((line = scan.readLine()) != null) word[next++] = line;
Try this.
Files.readAllLines(Paths.get("test.txt"))
.parallelStream()
.sorted(new ComImpl())
.forEach(System.out::println);
I'm just trying to do an exercise where I have to read a particular file called test.txt in the following format:
Sampletest 4
What I want to do is that I want to store the text part in one variable and the number in another. I am still a beginner so I had to google quite a bit to find something that would at-least work, here what I got so far.
public static void main(String[] args) throws Exception{
try {
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
} catch(IOException e) {
System.out.println("File not found");
}
Use a Scanner, which makes reading your file way easier than DIY code:
try (Scanner scanner = new Scanner(new FileInputStream("test.txt"));) {
while(scanner.hasNextLine()) {
String name = scanner.next();
int number = scanner.nextInt();
scanner.nextLine(); // clears newlines from the buffer
System.out.println(str + " and " + number);
}
} catch(IOException e) {
System.out.println("File not found");
}
Note the use of the try-with-resources syntax, which closes the scanner automatically when the try is exited, usable because Scanner implements Closeable.
You just need:
String[] parts = str.split(" ");
And parts[0] is the text (sampletest)
And parts[1] is the number 4
It seems like you are reading the whole file content (from test.txt file) line by line, so you need two separate List objects to store the numeric and non-numeric lines as shown below:
String str;
List<Integer> numericValues = new ArrayList<>();//stores numeric lines
List<String> nonNumericValues = new ArrayList<>();//stores non-numeric lines
while((str = br.readLine()) != null) {
if(str.matches("\\d+")) {//check line is numeric
numericValues.add(str);//store to numericList
} else {
nonNumericValues.add(str);//store to nonNumericValues List
}
}
If you are sure the format is always for each line in the file.
String str;
List<Integer> intvalues = new ArrayList<Integer>();
List<String> charvalues = new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
while((str = br.readLine()) != null) {
String[] parts = str.split(" ");
charvalues.add(parts[0]);
intvalues.add(new Integer(parts[0]));
}
}catch(IOException ioer) {
ioer.printStackTrace();
}
You can use java utilities Files#lines()
Then you can do something like this. Use String#split() to parse each line with a regular expression, in this example i use a comma.
public static void main(String[] args) throws IOException {
try (Stream<String> lines = Files.lines(Paths.get("yourPath"))) {
lines.map(Representation::new).forEach(System.out::println);
}
}
static class Representation{
final String stringPart;
final Integer intPart;
Representation(String line){
String[] splitted = line.split(",");
this.stringPart = splitted[0];
this.intPart = Integer.parseInt(splitted[1]);
}
}
What I'm looking to do here is process a log file, in my case it's squid's access.log. I want to have my program take a look at the first 'word' in the file, which is the time in Unix format of when the URL was accessed. In other parts of the program, I designed a time class, which gets the time the program was last run in Unix time, and I want to compare this time to the first word in the file, which happens to be a Unix time.
My initial thinking on how to do this is that I process the file, store it in array, then based on the first word in the file, omit the lines by removing it from the array that the processed file is in, and put it in another array
Here's what I've got so far. I'm pretty sure that I'm close, but this is the first time that I've done file processing, so I don't exactly know what I'm doing here.
private void readFile(File file) throws FileNotFoundException, IOException{
String[] lines = new String[getLineCount(file)];
Long unixTime = time.getUnixLastRun();
String[] removedTime = new String[getLineCount(file)];
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
int i = 0;
for(String line; (line = br.readLine()) != null; i++) {
lines[i] = line;
}
}
for(String arr: lines){
System.out.println(arr);
}
}
private void readFile(File file) {
List<String> lines = new ArrayList<String>();
List<String> firstWord = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
// Adds the entire first line
lines.add(sCurrentLine);
// Adds the first word
firstWord.add(sCurrentLine.split(" ")[0]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
If you want you can use your arrays.
private void readFile(File file) throws FileNotFoundException, IOException {
String[] lines = new String[getLineCount(file)];
Long unixTime = time.getUnixLastRun();
String[] removedTime = new String[getLineCount(file)];
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
int i = 0;
for (String line; (line = br.readLine()) != null; i++) {
lines[i] = line;
}
}
ArrayList<String> logsToBeUsed = new ArrayList<String>();
for (String arr : lines) {
//Gets the first word from the line and compares it with the current unix time, if it is >= unix time
//then we add it to the list of Strings to be used
try{
if(Long.parseLong(getFirstWord(arr)) >= unixTime){
logsToBeUsed.add(arr);
}
}catch(NumberFormatException nfe){
//Means the first word was not a float, do something here
}
}
}
private String getFirstWord(String text) {
if (text.indexOf(' ') > -1) {
return text.substring(0, text.indexOf(' '));
} else {
return text;
}
}
This is the answer according to the code you posted. This can be done more efficiently as you can use an ArrayList to store the lines from the file rather than first reading the line number getLineCount(file) as you open the file twice. And in the for loop you are declaring the String object again and again.
Rod
Rae
Bryan
Shiroe
Ric
Kirito
Asuna
Elsa
Akutabe
Shino
I have that list saved in a text file. If I were to enter Rod, it should say "Exists" and if I enter a name that is not on the list, it should say "Does not exist." But what is happening on my code is that it reads the file per line and prints "Does not exist" if it does not match the string line.
So if I were to enter a name that does not exist in the txt file, it would print 10 "Does not exist" lines.
This is my code below:
Scanner in = new Scanner(System.in);
out.print("Enter name: ");
String name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
out.println("Exists");
break;
} else {
out.println("Does not exist");
}
}
br.close();
An example of a what would be output is:
name = Kirito
Does not exist
Does not exist
Does not exist
Does not exist
Exists
Why does my program print so many Does not exist before finding the exact match?
Use a boolean to remember whether you have found a match, and display "Does not exist" only after checking every item and only if you have not found a match.
You were almost there. You are just preemptively printing the error message. I would have also used equals instead of contains and pre-loaded the entire file into. HashSet if multiple queries need to be answered
Scanner in = new Scanner(System.in);
out.print("Enter name: ");
String name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
boolean found = false;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
out.println("Exists");
found = true;
break;
}
}
if (!found) {
out.println("Does not exist");
}
br.close();
You're breaking the loop if the name exists, so you should only print the "not exists" message if the loop doesn't break:
Scanner in = new Scanner(System.in);
out.print("Enter name: ");
String name = in.nextLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
boolean nameFound = false;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
out.println("Exists");
nameFound = true;
break;
}
if (!nameFound) {
out.println("Does not exist");
}
br.close();
PrintStream out = System.out;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
out.print("Enter name: ");
String name = in.readLine();
BufferedReader br = new BufferedReader(new FileReader("name.txt"));
String line;
boolean ifexist = false;
while ((line = br.readLine()) != null) {
if (line.contains(name)) {
ifexist = true;
break;
}
}
if (ifexist) {
out.print("Exist");
} else {
out.println("Does not exist");
}
br.close();
Add a boolean var default false, when exist set it to true and break. Than output.
I need to add the contents of every line (single word) of an user input text file into a separate element in an array.
*I know an ArrayList is a better data structure for this problem but I am limited to using only an array.
Here is my code:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
FileReader reader = new FileReader(file);
try (BufferedReader buffReader = new BufferedReader(reader)) {
String line;
int i=0;
String[] words = new String[10];
while((line = buffReader.readLine()) != null) {
words[i]=buffReader.readLine();
System.out.println(words[i]);
i++;
}
}
catch(IOException e){
System.out.println(e);
}
}
The input file is simply:
Pans
Pots
opt
sit
it's
snap
Program output is below. It seems to be skipping every other line.
Pots
sit
snap
You are reading two lines per while loop iteration, one in the while condition, and the other in the first line of the loop body. The result is that each iteration consumes two lines, and only the second of the two is printed.
Eliminate the second call in the loop body, so that you have one iteration of the loop (and one print statement) per line.
Change the while loop as shown below. If while loop condition check, you are reading the line then again reading the line in first line in your while loop. So you are reading two lines and printing only one line.
while((line = buffReader.readLine()) != null) {
System.out.println(line );
i++;
}
while((line = buffReader.readLine()) != null)
That line read and consumed the first input line and that is why you are not seeing Pans and the even indexed inputs.
Can you use an ArrayList than just convert it to an Array using the toArray method? What are your limitations and why?
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
FileReader reader = new FileReader(file);
try (BufferedReader buffReader = new BufferedReader(reader)) {
String line;
int i=0;
String[] words = new String[10];
//modify line = buffReader.readLine()
while((words[i]=buffReader.readLine()) != null) {
//modify //words[i]=buffReader.readLine();
//words[i]=buffReader.readLine();
System.out.println(words[i]);
i++;
}
}
catch(IOException e){
System.out.println(e);
}
}