This program is meant to see two files located in a particular folder and then merge those two files and create a third file which is does. From the third merged file it is then searching for a keyword such as "test", once it finds that key word it prints out the location and the line of the keyword which is what is somewhat doing. What is happening is when I run the program it stops after the finds the keyword the first time in a line but it will not continue to search that line. So if there is multiple keyword 'test' in the line it will only find the first one and spit back the position and line. I want it to print both or multiple keywords. I think it is because of the IndexOf logic which is causing the issue.
import com.sun.deploy.util.StringUtils;
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Concatenate {
public static void main(String[] args) {
String sourceFile1Path = "C:/Users/me/Desktop/test1.txt";
String sourceFile2Path = "C:/Users/me/Desktop/test2.txt";
String mergedFilePath = "C:/Users/me/Desktop/merged.txt";
File[] files = new File[2];
files[0] = new File(sourceFile1Path);
files[1] = new File(sourceFile2Path);
File mergedFile = new File(mergedFilePath);
mergeFiles(files, mergedFile);
stringSearch(args);
}
private static void mergeFiles(File[] files, File mergedFile) {
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, true);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stringSearch(String args[]) {
try {
String stringSearch = "test";
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/me/Desktop/merged.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file");
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
}
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
It's because you are searching for the word once per line in your while loop. Each iteration of the loop takes you to the next line of the file because you are calling bf.readLine(). Try something like the following. You may have to tweak it but this should get you close.
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
while(indexfound > -1)
{
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
indexfound = line.indexOf(stringSearch, indexfound);
}
}
Related
I'm trying to find an object in a list from a text file
Example:
L;10;€10,50;83259875;YellowPaint
-H;U;30;€12,00;98123742;Hammer
G;U;80;€15,00;87589302;Seeds
By inserting 98123742 by input with scanner, i want to find that string.
I tried to do this:
private static void inputCode() throws IOException {
String code;
String line = null;
boolean retVal = false;
System.out.println("\ninsert code: ");
code = in.next();
try {
FileReader fileReader = new FileReader("SHOP.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] token = line.split(";");
if (token[0].equals(code) && token[1].equals(code)) {
retVal = true;
System.out.println(line);
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("impossible open the file " + fileName);
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
System.out.println(retVal);
}
How can i print "-H;U;30;€12,00;98123742;Hammer" inserting "98123742" (that is the code of the product) ?
Why are you splitting in the first place? For such a simple usecase, and with that line format, I'd go with
line.contains(";" + code);
Not much else to do.
My problem is that StringTokenizer seems to only read the first line of ip.txt
What I'm trying to do is load a list of IP addresses from "ip.txt" and save it into an array to automatically ping devices on my network to see if their online. No matter what I try I can't get more than the first line in "ip.txt" into the array. My delimiter is "//" and the name of the ip address is also stored in the txt file. I included the code and a sample of the text file.
Thanks in advance!!
public class IP {
public static IP[] ips = new IP[100];
public static int total_ips=0;
String name;
String ip1;
String ip2;
String ip3;
String ip4;
String fullIP;
public static void read_ips() throws FileNotFoundException{
FileInputStream fstream1 = new FileInputStream("ip.txt");
String line;
String delimiter = "//";
StringTokenizer tokenizer;
BufferedReader input = null;
try {
int i = 0;
int totalIps = 0;
input = new BufferedReader(new InputStreamReader(fstream1));
line = input.readLine();
//outer while
while(line != null) {
tokenizer = new StringTokenizer(line, delimiter);
while(tokenizer.hasMoreElements()) {//process tokens in line
ips[i] = new IP();
ips[i].name = tokenizer.nextToken();
ips[i].ip1 = tokenizer.nextToken();
ips[i].ip2 = tokenizer.nextToken();
ips[i].ip3 = tokenizer.nextToken();
ips[i].ip4 = tokenizer.nextToken();
ips[i].fullIP = ips[i].ip1+"."+ips[i].ip2+"."+ips[i].ip3+"."+ips[i].ip4;
i++;
totalIps = i;
System.out.println(line);
}
line = input.readLine(); //next line
}//close outer while
total_ips = totalIps; // count of total cars
System.out.println("total_ips after i++ "+total_ips);
}catch (FileNotFoundException e) {
System.out.println("Unable to open file " + fstream1);
} catch (IOException e) {
System.out.println("Unable to read from file " + fstream1);
}finally {
// Close the file
try {
if (input != null)
input.close();
} catch (IOException e) {
System.out.println("Unable to close file " + fstream1);
}
}
}
}
And here is an example of ip.txt
Desktop1//192//168//1//127//
Desktop2//192//168//1//128//
Desktop3//192//168//1//129//
Your code should be working fine. The more classic approach to iterate over the BufferedReader one line at a time is by using an expression like:
while ( (line = input.readLine()) != null) {.
That's about the only refactoring I did to your code and it is working. You may want to print the fullIP in order to check that you are correctly retrieving it.
Here is the code:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class IP {
public static IP[] ips = new IP[100];
public static int total_ips=0;
String name;
String ip1;
String ip2;
String ip3;
String ip4;
String fullIP;
public static void main(String[] args) throws IOException {
read_ips();
}
public static void read_ips() throws FileNotFoundException{
FileInputStream fstream1 = new FileInputStream("c:\\ips\\ip.txt");
String line;
String delimiter = "//";
StringTokenizer tokenizer;
BufferedReader input = null;
try {
int i = 0;
int totalIps = 0;
input = new BufferedReader(new InputStreamReader(fstream1));
while ( (line = input.readLine()) != null) {
tokenizer = new StringTokenizer(line, delimiter);
while(tokenizer.hasMoreElements()) {//process tokens in line
ips[i] = new IP();
ips[i].name = tokenizer.nextToken();
ips[i].ip1 = tokenizer.nextToken();
ips[i].ip2 = tokenizer.nextToken();
ips[i].ip3 = tokenizer.nextToken();
ips[i].ip4 = tokenizer.nextToken();
ips[i].fullIP = ips[i].ip1+"."+ips[i].ip2+"."+ips[i].ip3+"."+ips[i].ip4;
System.out.println(ips[i].fullIP);
i++;
totalIps = i;
System.out.println(line);
}
}
total_ips = totalIps; // count of total cars
System.out.println("total_ips after i++ "+total_ips);
}catch (FileNotFoundException e) {
System.out.println("Unable to open file " + fstream1);
} catch (IOException e) {
System.out.println("Unable to read from file " + fstream1);
}finally {
// Close the file
try {
if (input != null)
input.close();
} catch (IOException e) {
System.out.println("Unable to close file " + fstream1);
}
}
}
}
And an illustration:
i want to print the output in new line how to do this?
Below is the output.
CHILD: Child line one oneCHILD: Child line one twoCHILD: Child line one three
CHILD: Child line two oneCHILD: Child line two twoCHILD: Child line two three
here is my code for it...
try {
fis = new FileInputStream(file);
fileWriterChild = new FileWriter(outputFileForChild);
brChild = new BufferedWriter(fileWriterChild);
fr = new FileReader(file);
br = new BufferedReader(fr);
int child_line_no = 0;
int buffer = 0;
String currentLine = br.readLine();
while (currentLine != null) {
if (currentLine.contains("CHILD:")) {
Files.write(Paths.get("C:/output.child.txt"),
currentLine.getBytes(), StandardOpenOption.APPEND);
}
currentLine = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
fis.close();
}
}
Depends on what do you want to do. Here are my two ways:
Appending one line to the end of file
void WriteLog(String date, String message) {
String logFileName = <path to file>;
File logFile = new File(logFileName);
//make directories
logFile.getParentFile().mkdirs();
try (FileWriter writer = new FileWriter(logFile, true)) {
writer.write(message);
writer.write("\r\n");
} catch (IOException ex) {
Cls_log.LogError("Error writing log - " + ex.toString());
}
}
Writing all strings as lines to file (overwriting file)
public static void WriteABcardLog(Map<String,String> etiquetteCache) {
File logFile = new File(<path to file>);
logFile.getParentFile().mkdirs();
try (PrintWriter writer = new PrintWriter(logFile)) {
Iterator<Map.Entry<String, String>> iterator = etiquetteCache.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
try {
writer.print(entry.getKey() + ";" + entry.getValue() + "\r\n");
} catch (NullPointerException e) {
Cls_log.LogError(e);
}
}
writer.println();
} catch (IOException ex) {
Cls_log.LogError("Error writing etiquette log - " + ex.toString());
}
}
I am trying to design two different methods for a Java application. The first method will pass in a string of the name of a file, and return the text of a text file as a string. The second method will pass in the name of a file and the text, and create a new text file and output the string into the file.
Currently my code works without the methods, but I am trying to design it with a separation of concerns and low coupling. I am trying to modify it so I can just call a method to output any sort of data I have in a string to a text file.
Here is my code without the methods:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
//What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
//What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
//Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: " + outputFile);
// Variables to read and write the files
//Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
}
When creating a method for each of the "read" and "write" portions of my code, I constantly get errors that I assume are from the exception handling. Any thoughts on how to separate code that has exceptions involved?
Think in terms of single responsibility. You have two distinct operations that need to happen: reading and writing.
Let's start with reading. What you're doing right now to read the file surmises these lines:
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
Move that to a method.
private static String readFile(String inputFile) throws IOException {
BufferedReader input;
String total;
String line;// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
return total;
}
Here's what we did:
We have a variable total which is used elsewhere in the program, so that usage has to be preserved. We're returning String and will declare total = readFile(inputFile); on the outside.
We've changed nothing. This code will run the same way as it did without the method.
Now, if we want to move the writing functionality, which is:
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
...we just do.
private static void writeFile(String outputFile, String info) throws IOException {
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
}
Again, nothing's changed on this method. We don't have any other usages of any of the variables in here to worry about, so we can directly bring it across.
All said, that try block looks a bit anemic:
try {
total = readFile(inputFile);
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
writeFile(outputFile, info);
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
...which is a good thing.
I am not sure what are you asking about but try to create your own Exceptions and make your methods throw them like this
package com.qmic.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
// What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
// What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
// Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: "
+ outputFile);
// Variables to read and write the files
// Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
String readData = readFileContents(inputFile);
// Check to make sure we got the text files data
System.out.println("The total string says: \n" + readData);
// Call the reverseWords method to switch 'Hello' with 'World'
String reversedContents = reverseWords(readData);
writeToFile(outputFile, reversedContents);
} catch (ReadException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
} catch (WriteException ex) {
System.out.println("Error Writing file '" + outputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
public static void writeToFile(String fileName, String data)
throws WriteException {
BufferedWriter output = null;
try {
// Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + data);
File file = new File(fileName);
output = new BufferedWriter(new FileWriter(file));
output.write(data);
System.out.println("The output file: " + fileName
+ " has been written.");
}catch(IOException e){
throw new WriteException();
}finally{
try {
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String readFileContents(String fileName) throws ReadException {
// FileReader reads text files in the default encoding.
BufferedReader input = null;
String line = null;
String total = null;
try {
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
} catch (IOException e) {
throw new ReadException();
}finally{
//This is ugly code, if you are using java 7 you have extra option to better this
try {
input.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return total;
}
}
//make me public and move me to a separate file
class WriteException extends IOException {
}
//make me public and move me to a separate file
class ReadException extends IOException {
}
The "Number of Lines = 4" shows it's reading all 4 lines of the text file.
But then "Line read = null". I don't know why the readLine() method is not reading the first line.
import java.io.*;
public class TestLineRead {
public static void main (String[] args)
{
try
{
File tmpFileIn = new File("C:/Java/Employees.txt");
BufferedReader br = new BufferedReader (new InputStreamReader(
new FileInputStream(tmpFileIn)));
LineNumberReader lnr = new LineNumberReader(br);
int numOfLines = 0;
while (lnr.readLine() != null) {
numOfLines++;
}
String str = null;
System.out.println("Number of lines = " + numOfLines);
str = br.readLine();
System.out.println("Line read = " + str);
br.close();
}
catch (IOException e) { System.out.println("error: " + e.getMessage()); }
} // close main
} // close Class
I don't know why the readLine() method is not reading the first line.
It did, when you were counting lines.
This
while (lnr.readLine() != null) {
numOfLines++;
}
consumes lines. It returns null when there are no more lines left.