usage of stringtokenizer in java to display selected contents from a file - java

Can any one suggest, how to use string-tokens in java, to read all data in a file, and display only some of its contents. Like, if i have
apple = 23456, mango = 12345, orange= 76548, guava = 56734
I need to select apple, and the value corresponding to apple should be displayed in the output.
This is the code
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
public class ReadFile {
public static void main(String[] args) {
try {
String csvFile = "Data.txt";
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader(new FileReader(csvFile));
String line = "";
StringTokenizer st = null;
int lineNumber = 0;
int tokenNumber = 0;
//read comma separated file line by line
while ((line = br.readLine()) != null) {
lineNumber++;
//use comma as token separator
st = new StringTokenizer(line, ",");
while (st.hasMoreTokens()) {
tokenNumber++;
//display csv values
System.out.print(st.nextToken() + " ");
}
System.out.println();
//reset token number
tokenNumber = 0;
}
} catch (Exception e) {
System.err.println("CSV file cannot be read : " + e);
}
}
}
this is the file I'm working on :
ImageFormat=GeoTIFF
ProcessingLevel=GEO
ResampCode=CC
NoScans=10496
NoPixels=10944
MapProjection=UTM
Ellipsoid=WGS_84
Datum=WGS_84
MapOriginLat=0.00000000
MapOriginLon=0.00000000
ProdULLat=18.54590200
ProdULLon=73.80059300
ProdURLat=18.54653200
ProdURLon=73.90427600
ProdLRLat=18.45168500
ProdLRLon=73.90487900
ProdLLLat=18.45105900
ProdLLLon=73.80125300
ProdULMapX=373416.66169100
ProdULMapY=2051005.23286800
ProdURMapX=384360.66169100
ProdURMapY=2051005.23286800
ProdLRMapX=373416.66169100
ProdLRMapY=2040509.23286800
ProdLLMapX=384360.66169100
ProdLLMapY=2040509.23286800
Out of this, i need to display only the following :
NoScans
NoPixels
ProdULLat
ProdULLon
ProdLRLat
ProdLRLon

public class Test {
public String getValue(String str, String strDelim, String keyValueDelim, String key){
StringTokenizer tokens = new StringTokenizer(str, strDelim);
String sentence;
while(tokens.hasMoreElements()){
sentence = tokens.nextToken();
if(sentence.contains(key)){
return sentence.split(keyValueDelim)[1];
}
}
return null;
}
public static void main(String[] args) {
System.out.println(new Test().getValue("apple = 23456, mango = 12345, orange= 76548, guava = 56734", ",", "=", "apple"));
}
}
" I noticed you have edited your question and added your code. for your new version question you can still simply call method while reading the String from the file and get your desire value ! "

I have written code assuming you have already stored data from file to a String,
public static void main(String[] args) {
try {
String[] CONSTANTS = {"apple", "guava"};
String input = "apple = 23456, mango = 12345, orange= 76548, guava = 56734";
String[] token = input.split(",");
for(String eachToken : token) {
String[] subToken = eachToken.split("=");
// checking whether this data is required or not.
if(subToken[0].trim().equals(CONSTANTS[0]) || subToken[0].trim().equals(CONSTANTS[1])) {
System.out.println("No Need to do anything");
} else {
System.out.println(subToken[0] + " " + subToken[1]);
}
}
} catch(Exception e) {
e.printStackTrace();
}
}

read a complete line using bufferedreader and pass it to stringtokenizer with tokenizer as "="[as you mentioned in your file].
for more please paste your file and what you have tried so far..
ArrayList<String> list = new ArrayList<String>();
list.add("NoScans");
list.add("NoPixels");
list.add("ProdULLat");
list.add("ProdULLon");
list.add("ProdLRLat");
list.add("ProdLRLon");
//read a line from a file.
while ((line = br.readLine()) != null) {
lineNumber++;
//use 'equal to' as token separator
st = new StringTokenizer(line, "=");
//check for tokens from the above string tokenizer.
while (st.hasMoreTokens()) {
String key = st.nextToken(); //this will give the first token eg: NoScans
String value = st.nextToken(); //this will give the second token eg:10496
//check the value is present in the list or not. If it is present then print
//the value else leave it as it is.
if(list.contains(key){
//display csv values
System.out.print(key+"="+ " "+value);
}
}

Related

Java: Read file as long as a new date is found

I want to read the file and add each entry to an arraylist on a date. But the date should also be included.
File Example:
15.09.2002 Hello, this is the first entry.
\t this line, I also need in the first entry.
\t this line, I also need in the first entry.
\t this line, I also need in the first entry.
17.10.2020 And this ist the next entry
I tried this. But the Reader reads only the first Line
public class versuch1 {
public static void main(String[] args) {
ArrayList<String> liste = new ArrayList<String>();
String lastLine = "";
String str_all = "";
String currLine = "";
try {
FileReader fstream = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fstream);
while ((currLine = br.readLine()) != null) {
Pattern p = Pattern
.compile("[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2} [0-2]?[0-9]:[0-6]?[0-9]:[0-5]");
Matcher m = p.matcher(currLine);
if (m.find() == true) {
lastLine = currLine;
liste.add(lastLine);
} else if (m.find() == false) {
str_all = currLine + " " + lastLine;
liste.set((liste.indexOf(currLine)), str_all);
}
}
br.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.print(liste.get(0) + " "+liste.get(1);
}
}
I have solved my problem :)
public class versuch1 {
public static void main(String[] args) {
ArrayList<String> liste = new ArrayList<String>();
String lastLine = "";
String currLine = "";
String str_all = "";
try {
FileReader fstream = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fstream);
currLine = br.readLine();
while (currLine != null) {
Pattern p = Pattern
.compile("[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2} [0-2]?[0-9]:[0-6]?[0-9]:[0-5]");
Matcher m = p.matcher(currLine);
if (m.find() == true) {
liste.add(currLine);
lastLine = currLine;
} else if (m.find() == false) {
liste.set((liste.size() - 1), (str_all));
lastLine = str_all;
}
currLine = br.readLine();
str_all = lastLine + currLine;
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.print(liste.get(1) + " ");
}
}
While reading the lines, keep a "current entry".
If the line read begins with a date, then it belongs to a new entry. In this case add the current entry to the list of entries and create a new current entry consisting of the read line.
If the line did not begin with a date, just add it to the current entry.
For this to work, you need to read the first line into the current entry before the loop. And after the loop you need to add the current entry to the list of entries. This in turn only works if there is at least one line and the first line begins with a date. So handle the special case of no lines specially (use if-else). And report an error if the first line does not begin with a date.
Happy coding.

Compare user string input to a string from a textfile

I'm trying to do a simple login from a textfile. I've used different ways of reading the text from the file to a String line(BufferedReader and Scanner). I am able to get the line into a string, but it doesn't want to compare the 2 strings and match when I use an if statement(.equals()) or even if I use .equalsIgnoreCase(). When I print the 2 strings to be compared they are the same. but my if statement doesn't seem to return true?
This was the last coding i tried (I thought maybe if I put it into an array it would compare true, but still nothing).
Iv'e looked and saw similar questions to comparing strings from textfile, but never saw a problem with the if statement to return true
import java.io.*;
import java.text.*;
import java.lang.*;
public class tes
{
public static void main(String[] args)throws Exception
{
String logline = "JMX^1234";
ArrayList<String> lines = new ArrayList<String>();
FileReader fr = new FileReader("/home/jmx/Desktop/javap/Bank/jm.txt");
BufferedReader br = new BufferedReader(fr);
String rline = br.readLine();
while(rline != null)
{
lines.add(rline);
rline = br.readLine();
}
String[] users = new String[lines.size()];
lines.toArray(users);
for(int i = 0; i < users.length; i++)
{
if(logline.equals(users[i]))
{
System.out.println("Matched");
}
}
System.out.println("Login line: " + logline);
System.out.println("Text Line: " + users[0]);
br.close();
fr.close();
}
}
I've tried to execute your code and everything worked as expected. I received "matched". Maybe it's some kind of encoding issue. Try to compare length and if it is ok, try to leave only one line in the file and try this code:
String logline = "JMX^1234";
ArrayList<String> lines = new ArrayList<String>();
FileReader fr = new FileReader("/home/jmx/Desktop/javap/Bank/jm.txt");
BufferedReader br = new BufferedReader(fr);
String rline = br.readLine();
while(rline != null)
{
lines.add(rline);
rline = br.readLine();
}
String[] users = new String[lines.size()];
lines.toArray(users);
for (char ch : users[0].toCharArray()) {
System.out.print((int)ch);
}
System.out.println();
for (char ch : logline.toCharArray()) {
System.out.print((int)ch);
}
System.out.println();
for(int i = 0; i < users.length; i++)
{
if(logline.equals(users[i]))
{
System.out.println("Matched");
}
}
System.out.println("Login line: " + logline);
System.out.println("Text Line: " + users[0]);
br.close();
fr.close();
It should return equal lines of numbers like this:
7477889449505152
7477889449505152
Matched
Login line: JMX^1234
Text Line: JMX^1234
Also try to check out this answer: https://stackoverflow.com/a/4210732/6226118

Search for multiline String in a text file

I have a text file from which i am trying to search for a String which has multiple lines. A single string i am able to search but i need multi line string to be searched.
I have tried to search for single line which is working fine.
public static void main(String[] args) throws IOException
{
File f1=new File("D:\\Test\\test.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
String input="line one";
// here i want to search for multilines as single string like
// String input ="line one"+
// "line two";
int count=0;
while((s=br.readLine())!=null)
{
words=s.split("\n");
for (String word : words)
{
if (word.equals(input))
{
count++;
}
}
}
if(count!=0)
{
System.out.println("The given String "+input+ " is present for "+count+ " times ");
}
else
{
System.out.println("The given word is not present in the file");
}
fr.close();
}
And below are the file contents.
line one
line two
line three
line four
Use the StringBuilder for that, read every line from file and append them to StringBuilder with lineSeparator
StringBuilder lineInFile = new StringBuilder();
while((s=br.readLine()) != null){
lineInFile.append(s).append(System.lineSeparator());
}
Now check the searchString in lineInFile by using contains
StringBuilder searchString = new StringBuilder();
builder1.append("line one");
builder1.append(System.lineSeparator());
builder1.append("line two");
System.out.println(lineInFile.toString().contains(searchString));
More complicated solution from default C (code is based on code from book «The C programming language» )
final String searchFor = "Ich reiß der Puppe den Kopf ab\n" +
"Ja, ich reiß' ich der Puppe den Kopf ab";
int found = 0;
try {
String fileContent = new String(Files.readAllBytes(
new File("puppe-text").toPath()
));
int i, j, k;
for (i = 0; i < fileContent.length(); i++) {
for (k = i, j = 0; (fileContent.charAt(k++) == searchFor.charAt(j++)) && (j < searchFor.length());) {
// nothig
}
if (j == searchFor.length()) {
++found;
}
}
} catch (IOException ignore) {}
System.out.println(found);
Why don't you just normalize all the lines in the file to one string variable and then just count the number of occurrences of the input in the file. I have used Regex to count the occurrences but can be done in any custom way you find suitable.
public static void main(String[] args) throws IOException
{
File f1=new File("test.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
String input="line one line two";
// here i want to search for multilines as single string like
// String input ="line one"+
// "line two";
int count=0;
String fileStr = "";
while((s=br.readLine())!=null)
{
// Normalizing the whole file to be stored in one single variable
fileStr += s + " ";
}
// Now count the occurences
Pattern p = Pattern.compile(input);
Matcher m = p.matcher(fileStr);
while (m.find()) {
count++;
}
System.out.println(count);
fr.close();
}
Use StringBuilder class for efficient string concatenation.
Try with Scanner.findWithinHorizon()
String pathToFile = "/home/user/lines.txt";
String s1 = "line two";
String s2 = "line three";
String pattern = String.join(System.lineSeparator(), s1, s2);
int count = 0;
try (Scanner scanner = new Scanner(new FileInputStream(pathToFile))) {
while (scanner.hasNext()) {
String withinHorizon = scanner.findWithinHorizon(pattern, pattern.length());
if (withinHorizon != null) {
count++;
} else {
scanner.nextLine();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(count);
Try This,
public static void main(String[] args) throws IOException {
File f1 = new File("./src/test/test.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String input = "line one";
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.contains(input)) {
count++;
}
}
if (count != 0) {
System.out.println("The given String " + input + " is present for " + count + " times ");
} else {
System.out.println("The given word is not present in the file");
}
fr.close();
}

Java - Reading a line from a file containing text and number

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

How to trim last 4 characters of each elements present in an arraylist in java?

I have imported a set of values into an array list from a csv file. Now i need to remove the extension .tar from each element or allow only first 8 characters to be inserted into the array list while importing it from a csv file. This is my code and i want that change in array1 part
import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.lang.*;
public class compare
{
public static void main(String[] args)
{
ArrayList<String> array = new ArrayList<String>(); //Array for storing values
ArrayList<String> array1 = new ArrayList<String>(); //Array for storing values
try
{
String strFile = "D:\\Ramakanth\\PT2573\\ftp.csv"; //csv file containing data
BufferedReader br = new BufferedReader( new FileReader(strFile)); //create BufferedReader to
String strLine = "";
StringTokenizer st = null;
while( (strLine = br.readLine()) != null) //read comma separated file line by line
{
st = new StringTokenizer(strLine, ","); //break comma separated line using ","
while(st.hasMoreTokens())
{
array.add(st.nextToken()); //store csv values in array
}
}
}
catch(Exception e)
{
System.out.println("Exception while reading csv file: " + e);
}
try
{
String strFile1 = "D:\\Ramakanth\\PT2573\\target.csv"; //csv file containing data
BufferedReader br1 = new BufferedReader( new FileReader(strFile1)); //create BufferedReader
String strLine1 = "";
StringTokenizer st1 = null;
while( (strLine1 = br1.readLine()) != null) //read comma separated file line by line
{
st1 = new StringTokenizer(strLine1, ","); //break comma separated line using ","
while(st1.hasMoreTokens())
{
array1.add(st1.nextToken()); //store csv values in array
}
}
}
catch(Exception e)
{
System.out.println("Exception while reading csv file: " + e);
}
array.removeAll(array1);
System.out.println(array);
try
{
BufferedWriter br2 = new BufferedWriter(new FileWriter("D:\\Ramakanth\\PT2573\\output.csv"));
StringBuilder sb1 = new StringBuilder();
for (String element : array)
{
sb1.append(element);
sb1.append(" ");
}
br2.write(sb1.toString());
br2.close();
}
catch(Exception e)
{
System.out.println("Exception while writing csv file: " + e);
}
}
}
Try this,
String element = "extension.tar";
int index = element.lastIndexOf(".");
System.out.println("if Dot extension means : " + element.substring(0, index));
element = element.substring(0, 8);
System.out.println("if first 8 character means : " + element);
output:
if Dot extension means : extension
if first 8 character means : extensio
You can do by using StringUtils.substringBefore class by using
StringUtils.substringBefore(yourstring, ".tar" );
It will give you the desired output

Categories

Resources