Java StringTokenizer only reading first line - java

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:

Related

Read, and then split a text file into different arrays

So I'm trying to use a BufferedReader to split a text file into 2 different arrays, I've written some code but I'm not sure where to go from here.
I know how to populate an array, but i just cant seem to get the specific lines.
So, one array for NEW_OFFICE containing only the numbers, and one for MAIN_ADDRESS containing only the numbers below it.
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("myDelivery.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String words = read.split("NEW_OFFICE")[0];
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception ignored) { }
}
This is the text file:
NEW_OFFICE
-92.48392883 52.96531732
-2.483984994 92.48392883
MAIN_ADDRESS
-1.207614869 52.98908196
NEW_OFFICE always is the first line, and always has two lines below
it, the same goes for MAIN_ADDRESS it always has one line below it.
NEW_OFFICE & MAIN_ADDRESS can't appear more than once.
Based on your comment mentioned above, given below is the solution:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
String[][] office = new String[2][2];
String[][] main = new String[1][2];
try (BufferedReader in = new BufferedReader(new FileReader("myDelivery.txt"))) {
String read;
while ((read = in.readLine()) != null) {
if (read.equalsIgnoreCase("NEW_OFFICE")) {
// Read next two lines
for (int i = 0; i < 2; i++) {
if ((read = in.readLine()) != null) {
office[i] = read.split("\\s+");
}
}
} else if (read.equalsIgnoreCase("MAIN_ADDRESS")) {
// Read next line
if ((read = in.readLine()) != null) {
main[0] = read.split("\\s+");
}
}
}
}
// Display office[][]
System.out.println("Displaying office:");
for (String[] officeData : office) {
System.out.println(Arrays.toString(officeData));
}
// Display main[][]
System.out.println("Displaying main:");
for (String[] mainData : main) {
System.out.println(Arrays.toString(mainData));
}
}
}
Output:
Displaying office:
[-92.48392883, 52.96531732]
[-2.483984994, 92.48392883]
Displaying main:
[-1.207614869, 52.98908196]
Notes:
\\s+ is for splitting the line on space(s).
Use try-with-resources syntax to simplify your code.
.split() does take a string, but it should be a regex, not the substring that you want to split it on. You want to change your code like this:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String read;
String office = "";
while ((read = in.readLine()) != null) {
if (read.contains("NEW_OFFICE")) {
office = "NEW_OFFICE";
} else if (read.contains("MAIN_ADDRESS")) {
office = "MAIN_ADDRESS";
} else {
System.out.println(office + " : " + read);
}
}
} catch (IOException e) {
e.printStackTrace();
}
I have also changed your try with try-with-resources so you don't have to worry about closing the resource.
I´d go with somethin like this.
Please be aware that I don´t have an IDE right now so this is basically pseudo code:
try (BufferedReader in = new BufferedReader(new FileReader("x.txt"))) {
String line = null;
boolean isOffice = false;
ArrayList<double> officeInts = new ArrayList<double>();
ArrayList<double> addressInts = new ArrayList<double>();
while ((line = in.readLine()) != null) {
if (line.contains("NEW_OFFICE")) {
isOffice = true;
continue;
} else if (line.contains("MAIN_ADDRESS")) {
isOffice = false;
continue;
}
for(String s : line.split(" "){
double num = Double.parseDouble(s);
if(isOffice) {
officeInts.add(num);
} else {
addressInts.add(num);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}

how to copy only a part of .CSV based on first column elements with java

copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}

Parsing strings with split JAVA

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.

Debugging File Search / Merge Code

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);
}
}

How to remove commas from a text file?

I got this far, but it seems that buffer won't take arrays, because first I had it this way
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
// System.out.println (strLine);
String Record = strLine;
String delims = "[,]";
String[] LineItem = Record.split(delims);
//for (int i = 0; i < LineItem.length; i++)
for (int i = 0; i == 7; i++)
{
System.out.print(LineItem[i]);
}
now I leave at this, because it's reading but not taking out commas.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class mainPro1test {
public static void main(String[] args) {
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\2010_Transactions.txt"));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
String Record = text;
String delims = "[,]";
String[] LineItem = Record.split(delims);
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
}
}
of how it should look like
input
Sell,400,IWM ,7/6/2010,62.481125,24988.02,4.43
Sell,400,IWM ,7/6/2010,62.51,24999.57,4.43
output
Sell 400 IWM 7/6/2010 62.481125 24988.02 4.43
Sell 400 IWM 7/6/2010 62.51 24999.57 4.43
If you only want to remove commas from a String, you can use String.replaceAll(",","");
If you want to replace them by spaces, use String.replaceAll(","," "):
while ((text = reader.readLine()) != null) {
contents.append(text.replaceAll(","," ");
}
Also in your code you seem to split the input, but don't use the result of this operation.
Easier is to define a new InputStream that just removes the commas...
class CommaRemovingStream extends InputStream {
private final InputStream underlyingStream;
// Constructor
#Override public int read() throws IOException {
int next;
while (true) {
next = underlyingStream.read();
if (next != ',') {
return next;
}
}
}
}
Now you can read the file without commas:
InputStream noCommasStream = new CommaRemovingStream(new FileInputStream(file));

Categories