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
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]);
}
}
I have a java file, FileJava.java like this:
public class FileJava {
public static void main(String args[]) {
for (int i = 0; i < 5; i++) {
}
}
}
Then, i read above code line by line using this code:
import java.util.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("FileJava.java");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("for"))
{
lines.add("long A=0;");
if(line.contains("(") && line.contains(")")){
String get = line;
String[] split = get.split(";");
String s1 = split[0];
String s2 = split[1];
String s3 = split[2];
}
}
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
The question is, how to read character between '(' and ')' inside (for) in the FileJava.java, the character i mean "int i = 0; i < 5; i++" that will be stored in a variable, i have split based on ";", but when i print, the value :
s1 = for (int i = 0
s2 = i < 5
s3 = i++) {
While i expect:
s1 = int i = 0
s2 = i < 5
s3 = i++
Thanks
To answer your question how to restrict the splitting to the parenthesized section:
String[] split =
get.substring( get.indexOf('(')+1, get.indexOf(')').split("\\s*;\\s*");
Edit to address another prob.
Printing of the file will all happen in one line, because BufferedReader.readLine strips the line ends (LF, CRLF) from the line it returns. Thus, add a line break when writing:
for(String s : lines){
out.write(s);
out.newLine();
}
int index1 = line.indexOf("(");
int index2 = line.indexOf(")");
line = line.subString(index1 + 1, index2);
Its because you are splitting on ';' for the input
for (int i = 0; i < 5; i++) {
which will return all the characters between ';'
You can write a new method, called getBracketContent for example, that will be something like
String getBracketContent(String str)
{
int startIdx = str.indexOf('(')
int endIdx = str.indexOf(')')
String content = str.subString(startIdx + 1, endIdx);
}
then your code would be
if(line.contains("(") && line.contains(")")){
String get = getBracketContent(line);
String[] split = get.split(";");
Ideally I would use regular expressions to parse the information you need, but that is probably something you may want to look into later.
If you want to read the contents of a java file, you would be much better off using an AST (Abstract Syntax Tree) parser which will read in the contents of the file and then callback when it encounters certain expressions. In your case, you can listen just for the 'for' loop.
I have two related text files shown for example in data1.txt and data2.txt. I want to merge the two files to create result.txt. Any idea how to go about this?
data1.txt
books, 3
Shelf, 5
groceries,6
books, 1
Shelf, 2
data2.txt
books,2
shelf,3
groceries,1
result.txt
books, 3, 2
Shelf, 5,3
groceries,6,1
books, 1,2
Shelf, 2, 3
this is a example for you.first you need to add values to 2d list from data2 text file.and then when line is null in file2 you can get mapping value relative to it's text from that list .so i have a method which will return back the mapping value for a String .code is little long than i thought .i post only relevant methods here.This is link to complete class file
public void marged(){
try {
BufferedReader br1 = null;
BufferedReader br2 = null;
String line1;
String line2;
ArrayList<ArrayList<String>> arrayList = new ArrayList<>();
br1 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data1.txt"));
br2 = new BufferedReader(new FileReader("C:\\Users\\Madhawa.se\\Desktop\\workingfox\\data2.txt"));
while ((line1 = br1.readLine()) != null) {
String[] split1 = line1.split(",");
String line1word = split1[0].trim();
String line1val = split1[1].trim();
line2 = br2.readLine();
if (line2 != null) {
String[] split2 = line2.trim().split(",");
String line2word = split2[0].trim();
String line2val = split2[1].trim();
ArrayList<String> list = new ArrayList();
list.add(line2word);
list.add(line2val);
arrayList.add(list);
if (line1word.equalsIgnoreCase(line2word)) {
String ok = line1word + "," + line1val + "," + line2val;
System.out.println(ok);
}
} else {
String ok = line1word + "," + line1val + "," + doesexist(arrayList, line1word);
System.out.println(ok);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
this is the method return mapping value
public String doesexist(ArrayList<ArrayList<String>> arrayList, String s) {
for (int i = 0; i < arrayList.size(); i++) {
String get = arrayList.get(i).get(0);
if (get.trim().equalsIgnoreCase(s.trim())) {
return arrayList.get(i).get(1);
}
}
return "-1";
}
output>>
books,3,2
Shelf,5,3
groceries,6,1
books,1,2
Shelf,2,3
Simply add files into an array of File object then read it using loop.
File []files = new Files[amountOfFiles];
//initialize array elements
for(File f:files)
{
//read each file and store it into string variable
}
//finally write the string variable into result.txt file.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class SOQ21
{
public SOQ21()
{
merge();
}
public void merge()
{
try
{
String firstfile = "data1.txt";
FileReader fr1 = new FileReader(firstfile);
BufferedReader bfr1 = new BufferedReader(fr1);
String secondfile = "data2.txt";
FileReader fr2 = new FileReader(secondfile);
BufferedReader bfr2 = new BufferedReader(fr2);
/*
^^^ Right here is how you get the files and accompanying BufferedReaders
to handle them
*/
//next, using the readLine() method from the Java API, read each line
//for the first file
//then, separate by taking the words into an ArrayList and storing the
//numbers as Strings in a String[] of equal length of the ArrayList
//Do the same for the second file
//Then, if the word of ArrayList 1 matches the word of ArrayList 2,
//append the String numbers from String[] 2 to String[] 1
//DONE! :)
}
catch(FileNotFoundException ex)
{
//handle how you want
}
}
public static void main(String[] args)
{
SOQ21 soq = new SOQ21();
}
}
The comments I made should answer most of your questions. Lastly, I would pay special attention to the exceptions, I'm not entirely sure how you wanted to deal with that, but make sure you fill it with SOMETHING!
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);
}
}