I am new to Java. Can anybody suggest to me how to read a CSV file with 7 columns?
Here is my code:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class main {
public static Map<String,String> map1 = null;
public static Map<String,String> map2 = null;
public static void main(String[] args) {
try {
readFileandPopulate();
for (Map.Entry<String, String> entry : map1.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue()+" address :"+map2.get(entry.getKey()));
//insert into DB
}
} catch (Exception e) {//Catch exception if any
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
public static void readFileandPopulate() throws Exception {
FileInputStream fstream = new FileInputStream("/Users/Desktop/Pattern Recognition/DataSetR/1a19.csv");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
map1 = new HashMap<String,String>();
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
String temp[] = strLine.split(",");
map1.put(temp[0], temp[1]);
}
in.close();
System.out.println("done 1");
}
}
Is there any method to just read few columns and delete remaining data or can I store all values in array and use index of array to calculate one equation using values?
I would recommend using a CSV parser, such as http://opencsv.sourceforge.net/. Then you could do the following:
CSVReader reader = new CSVReader(new FileReader(filePath), ',');
List<String[]> rows= reader.readAll();
for (String[] row : rows)
{
for (int i = 0; i < numColumnsToParse; i++)
{
//do something with row[i]
}
}
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
public class ReadCSV
{
public static void main(String[] args) throws IOException
{
String[] row = null;
String csvFilename = "C:/Users/Hussain/Desktop/data.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
List content = csvReader.readAll();
for (Object object : content)
{
row = (String[]) object;
System.out.println("value in row 7 ===>>>"+row[6]);
}
csvReader.close();
}
}
you can add the jar from here
Related
I have created a class that allows the user to create and store compounds into a Hash Map and now I want to create another class that allows me to take the values stored in that Hash Map and save them into a text file. I'm not sure if this is needed, but here is the code for the first class that I created containing the Hash Map:
package abi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class ChemicalComp {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Map<String, String> data = new HashMap<String, String>();
while(true){
String readinput=br.readLine();
if(readinput.equals(""))
break;
String input = readinput.replaceAll("\"", "");
String array[]=input.split(", ");
String compound=array[0];
String formula="";
for(int i=1;i<array.length;i++){
if(!array[i].equals("1")){
formula+=array[i];
}
}
data.put(compound, formula);
}
if(!data.isEmpty()) {
#SuppressWarnings("rawtypes")
Iterator it = data.entrySet().iterator();
while(it.hasNext()) {
#SuppressWarnings("rawtypes")
Map.Entry obj = (Entry) it.next();
System.out.println(obj.getKey()+":"+obj.getValue());
}
}
}
}
I'm not too familiar with text files, but I have done some research and this is what I've gotten so far. I know its pretty basic and that I will probably need some type of getter method, but I'm not sure where to incorporate it into what I have. Here is what I have for the class containing the text file:
package abi;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class CompoundManager {
private String path;
private boolean append_to_file = false;
public CompoundManager(String file_path) {
path = file_path;
}
public CompoundManager(String file_path, boolean append_value){
path = file_path;
append_to_file = append_value;
}
public void WriteToFile (String textLine) throws IOException{
FileWriter Compounds = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter (Compounds);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}
I can't understand what your program does but you can use a buffered writer for it.
Just create a try-catch block and wrap a filewriter in a bufferedwriter like this :
try (BufferedWriter br = new BufferedWriter(new FileWriter(new File("filename.txt"))))
{
for (Map.Entry<Integer, String> entry : map.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
br.write(key + ": " + value);
br.newLine();
}
} catch (Exception e) {
printStackTrace();
}
I got this below program from an coding site.
The following code read text file and find duplicate words.
To read from each text files and display it's duplicate words count line by line.
And how to call that files if it is not stored as String, I used buffered reader but I am not getting my output.
My questions:
How can I make the program read multiple files from given folder?
How to save the results in Excel file format?
Any suggestions Welcomed.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;
public class MaxDuplicateWordCount {
public Map<String, Integer> getWordCount(String fileName){
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Map<String, Integer> wordMap = new HashMap<String, Integer>();
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while((line = br.readLine()) != null){
StringTokenizer st = new StringTokenizer(line, " ");
while(st.hasMoreTokens()){
String tmp = st.nextToken().toLowerCase();
if(wordMap.containsKey(tmp)){
wordMap.put(tmp, wordMap.get(tmp)+1);
} else {
wordMap.put(tmp, 1);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{if(br != null) br.close();}catch(Exception ex){}
}
return wordMap;
}
public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap){
Set<Entry<String, Integer>> set = wordMap.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
{
public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
return list;
}
public static void main(String a[]){
MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
Map<String, Integer> wordMap = mdc.getWordCount("E:\\Blog 39.txt");
List<Entry<String, Integer>> list = mdc.sortByValue(wordMap);
for(Map.Entry<String, Integer> entry:list){
System.out.println(entry.getKey()+" ="+entry.getValue());
}
}
}
Intro
After chatting with OP, here is briefly what OP requires:
1- Read file/s from specific folder, files are typically Unicode as text files.
2- The files will be process in OP Algorithm in the Question, and the results of the Algorithm should be saved on Unicode file again (Later OP asked to be saved as Excel file (.XLS) because of Unicode compatibility with Excel)
Solution
This can be solved in following steps:
step 1 We define (declare) our work-space
step 2 We create output folder in work-space if not exist
step 3 We read all existing files in work-space folder and process them in the Algorithm.
step 4 The results of each file will saved as Excel file in output folder.
The code
First of all you need to import POI package, this will allow you to create XLS sheet. I have downloaded this poi/poi-3.5-FINAL.jar.zip( 1,372 k) and the following imports should added to your code.
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
Next you added following code to your code, it is self explainable code:
final static String WORKSPACE = "C:/testfolder/";
private static void createOutputFolder(String outputFolderName) {
File outputDirectory = new File(WORKSPACE + outputFolderName);
if (!outputDirectory.exists()) {
try {
outputDirectory.mkdir();
} catch (Exception e) {
}
}
}
private static void exlCreator() {
String outputFolder = "output/";
String fileName, fileNameWPathInput;
int serialNumber = 1;
createOutputFolder(outputFolder);
MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
File folder = new File(WORKSPACE);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
fileName = listOfFiles[i].getName();
fileNameWPathInput = WORKSPACE + fileName;
Map<String, Integer> wordMap = mdc.getWordCount(fileNameWPathInput);
List<Entry<String, Integer>> list = mdc.sortByValue(wordMap);
String fileNameWPathOutput = WORKSPACE + outputFolder +
fileName.substring(0, fileName.length() - 4)
+ "output.xls";
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("ResultSheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(0).setCellValue("Serial No.");
rowhead.createCell(1).setCellValue("Word");
rowhead.createCell(2).setCellValue("Count");
for (Map.Entry<String, Integer> entry : list) {
HSSFRow row = sheet.createRow((short) serialNumber);
row.createCell(0).setCellValue(serialNumber);
row.createCell(1).setCellValue(entry.getKey());
row.createCell(2).setCellValue(entry.getValue());
serialNumber++;
}
FileOutputStream fileOut = new FileOutputStream(fileNameWPathOutput);
workbook.write(fileOut);
fileOut.close();
serialNumber = 1;
System.out.println(fileNameWPathOutput + " is created");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
public static void main(String [] args) throws IOException {
exlCreator();
}
Finally
By manipulating the code, it is possible to create one output file but create each output results in work sheets.
As you can see in the image below, the output file is opened in Excel showing Unicode text with out problem, as it was the issue in my first solution:
Links
Download POI
POI documentation
Unicode problem in CSV
More about CSV
Full code, requested from OP
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;
//for Excel ark
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
public class MaxDuplicateWordCount {
public Map<String, Integer> getWordCount(String fileName) {
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Map<String, Integer> wordMap = new HashMap<String, Integer>();
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " ");
while (st.hasMoreTokens()) {
String tmp = st.nextToken().toLowerCase();
if (wordMap.containsKey(tmp)) {
wordMap.put(tmp, wordMap.get(tmp) + 1);
} else {
wordMap.put(tmp, 1);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (Exception ex) {
}
}
return wordMap;
}
public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap) {
Set<Entry<String, Integer>> set = wordMap.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
return list;
}
final static String WORKSPACE = "C:/testfolder/";
private static void createOutputFolder(String outputFolderName) {
File outputDirectory = new File(WORKSPACE + outputFolderName);
if (!outputDirectory.exists()) {
try {
outputDirectory.mkdir();
} catch (Exception e) {
}
}
}
private static void exlCreator() {
String outputFolder = "output/";
String fileName, fileNameWPathInput;
int serialNumber = 1;
createOutputFolder(outputFolder);
MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
File folder = new File(WORKSPACE);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
fileName = listOfFiles[i].getName();
fileNameWPathInput = WORKSPACE + fileName;
Map<String, Integer> wordMap = mdc.getWordCount(fileNameWPathInput);
List<Entry<String, Integer>> list = mdc.sortByValue(wordMap);
String fileNameWPathOutput = WORKSPACE + outputFolder +
fileName.substring(0, fileName.length() - 4)
+ "output.xls";
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("ResultSheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(0).setCellValue("Serial No.");
rowhead.createCell(1).setCellValue("Word");
rowhead.createCell(2).setCellValue("Count");
for (Map.Entry<String, Integer> entry : list) {
HSSFRow row = sheet.createRow((short) serialNumber);
row.createCell(0).setCellValue(serialNumber);
row.createCell(1).setCellValue(entry.getKey());
row.createCell(2).setCellValue(entry.getValue());
serialNumber++;
}
FileOutputStream fileOut = new FileOutputStream(fileNameWPathOutput);
workbook.write(fileOut);
fileOut.close();
serialNumber = 1;
System.out.println(fileNameWPathOutput + " is created");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
public static void main(String[] args) throws IOException {
exlCreator();
}
}
Let say you have a directory with all the files you want to read from.
File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
/*
* Here if your file is not a text file
* If I undersood you correct:
* "And how to call that files if it is not stored as String"
* you can get it as byte[] and parse it to String
*/
byte[] bytes = Files.readAllBytes(file.toPath());
String decoded = new String(bytes, "UTF-8");
String[] words = decoded.split("\\s+");
for (int i = 0; i < words.length; i++) {
/* You may want to check for a non-word character before blindly
* performing a replacement
* It may also be necessary to adjust the character class
*/
words[i] = words[i].replaceAll("[^\\w]", "");
//Here are all the words from a file. You can do whatever you want with them
}
}
}
I have two text files,
a.txt
b.txt
Each text files contains some file paths. b.txt contains some more file paths than a.txt. I would like to determine which paths are added and which are removed from a.txt so that it corresponds to paths in b.txt.
For example,
abc.txt contains
E:\Users\Documents\hello\a.properties
E:\Users\Documents\hello\b.properties
E:\Users\Documents\hello\c.properties
and xyz.txt contains
E:\Users\Documents\hello\a.properties
E:\Users\Documents\hello\c.properties
E:\Users\Documents\hello\g.properties
E:\Users\Documents\hello\h.properties
Now how to find that g.prop and h.prop are added and b.prop is removed?
Could anyone explain how it is done? I could only find how to check for identical contents.
The below code will serve your purpose irrespective of the content of the file.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public Test(){
System.out.println("Test.Test()");
}
public static void main(String[] args) throws Exception {
BufferedReader br1 = null;
BufferedReader br2 = null;
String sCurrentLine;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
br1 = new BufferedReader(new FileReader("test.txt"));
br2 = new BufferedReader(new FileReader("test2.txt"));
while ((sCurrentLine = br1.readLine()) != null) {
list1.add(sCurrentLine);
}
while ((sCurrentLine = br2.readLine()) != null) {
list2.add(sCurrentLine);
}
List<String> tmpList = new ArrayList<String>(list1);
tmpList.removeAll(list2);
System.out.println("content from test.txt which is not there in test2.txt");
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i)); //content from test.txt which is not there in test2.txt
}
System.out.println("content from test2.txt which is not there in test.txt");
tmpList = list2;
tmpList.removeAll(list1);
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i)); //content from test2.txt which is not there in test.txt
}
}
}
The memory will be a problem as you need to load both files into the program.
I am using HashSet to ignore duplicates.Try this:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
public class FileReader1 {
public static void main(String args[]) {
String filename = "abc.txt";
String filename2 = "xyz.txt";
HashSet <String> al = new HashSet<String>();
HashSet <String> al1 = new HashSet<String>();
HashSet <String> diff1 = new HashSet<String>();
HashSet <String> diff2 = new HashSet<String>();
String str = null;
String str2 = null;
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
while ((str = in.readLine()) != null) {
al.add(str);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader in = new BufferedReader(new FileReader(filename2));
while ((str2 = in.readLine()) != null) {
al1.add(str2);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
for (String str3 : al) {
if (!al1.contains(str3)) {
diff1.add(str3);
}
}
for (String str5 : al1) {
if (!al.contains(str5)) {
diff2.add(str5);
}
}
for (String str4 : diff1) {
System.out.println("Removed Path: "+str4);
}
for (String str4 : diff2) {
System.out.println("Added Path: "+str4);
}
}
}
Output:
Removed Path: E:\Users\Documents\hello\b.properties
Added Path: E:\Users\Documents\hello\h.properties
Added Path: E:\Users\Documents\hello\g.properties
You can simple do follow
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(final String[] args) throws IOException {
final Path firstFile = Paths.get("/home/src/main/resources/a.txt");
final Path secondFile = Paths.get("/home/src/main/resources/b.txt");
final List<String> firstFileContent = Files.readAllLines(firstFile,
Charset.defaultCharset());
final List<String> secondFileContent = Files.readAllLines(secondFile,
Charset.defaultCharset());
System.out.println(diffFiles(firstFileContent, secondFileContent));
System.out.println(diffFiles(secondFileContent, firstFileContent));
}
private static List<String> diffFiles(final List<String> firstFileContent,
final List<String> secondFileContent) {
final List<String> diff = new ArrayList<String>();
for (final String line : firstFileContent) {
if (!secondFileContent.contains(line)) {
diff.add(line);
}
}
return diff;
}
}
Compare files [Scanner and ArrayList]:
protected static void compareFiles(String firstFile, String secondFile)
throws Exception {
Scanner x = new Scanner(new File(firstFile));
List<String> list1 = getScannerList(x);
x = new Scanner(new File(secondFile));
List<String> list2 = getScannerList(x);
x.close();
System.out.println("File Extras");
printLnList(listExtras(list1, new ArrayList<String>(list2)));
System.out.println("File Removals");
printLnList(listExtras(list2, list1));
}
protected static List<String> listExtras(List<String> list1,
List<String> list2) throws Exception {
list2.removeAll(list1);
return list2;
}
protected static List<String> getScannerList(Scanner sc) throws Exception {
List<String> scannerList = new ArrayList<String>();
while (sc.hasNext())
scannerList.add(sc.nextLine());
return scannerList;
}
protected static void printLnList(List<String> list) {
for (String string : list)
System.out.println(string);
}
Program output:
File Extras
E:\Users\Documents\hello\g.properties
E:\Users\Documents\hello\h.properties
File Removals
E:\Users\Documents\hello\b.properties
For example we have a .txt file:
Name smth
Year 2012
Copies 1
And I want to replace it with that:
Name smth
Year 2012
Copies 0
Using java.io.*.
Here is the code that does that. Let me know if you have any question.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;
public class Test2 {
Map<String, String> someDataStructure = new LinkedHashMap<String, String>();
File fileDir = new File("c:\\temp\\test.txt");
public static void main(String[] args) {
Test2 test = new Test2();
try {
test.readFileIntoADataStructure();
test.writeFileFromADataStructure();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void readFileIntoADataStructure() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileDir)));
String line;
while ((line = in.readLine()) != null) {
if (line != null && !line.trim().isEmpty()) {
String[] keyValue = line.split(" ");
// Do you own index and null checks here this is just a sample
someDataStructure.put(keyValue[0], keyValue[1]);
}
}
in.close();
}
private void writeFileFromADataStructure() throws IOException {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileDir)));
for (String key : someDataStructure.keySet()) {
// Apply whatever business logic you want to apply here
myBusinessMethod(key);
out.write(key + " " + someDataStructure.get(key) + "\n");
out.append("\r\n");
out.append("\r\n");
}
out.flush();
out.close();
}
private String myBusinessMethod(String data) {
if (data.equalsIgnoreCase("Copies")) {
someDataStructure.put(data, "0");
}
return data;
}
}
Read your original text file line by line and separate them into string tokens delimited by spaces for output, then when the part you want replaced is found (as a string), replace the output to what you want it to be. Adding the false flag to the filewrite object ("filename.txt", false) will overwrite and not append to the file allowing you to replace the contents of the file.
this is the code to do that
try {
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("yourFolder/theinputfile.txt" , false));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.indexOf("Copies")>=0){
bw.write("Copies 0")
}
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close()bw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
hopefully that help
i want to verify if a number for example 701234567 is an element of my array in java. For this, my code search if my number who is begening with 7 and have 9 digits is a element of my array "numbercall.txt" who have 5 elements. This is my text file:
numbercall.txt [ 702345678, 714326578, 701234567, 791234567,751234567]
This is my code:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestNumberLt {
static String[] arr= null;
String filename = "fichiers/numbercall.txt";
static String a = null ;
static List<String> list = new ArrayList<String>();
public static void main(String [] args) throws IOException{
FileInputStream fstream_school = new FileInputStream(filename);
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
list.add(str_line);
}
}
int b = 773214576;
//convert the arraylist to a array
arr = (String[])list.toArray(new String[list.size()]);
Pattern p = Pattern.compile("^7[0|6|7][0-9]{7}$");
Matcher m ;
//a loop for verify if a number exist in this array
for (int j = 0; j < list.size();)
{
System.out.print(" "+list.get(j)+ " ");
m = p.matcher(list.get(j));
/*while(m.find())
System.out.println(m.group());*/
if(list.get(j).equals(b))
{
System.out.println("Trouvé "+list.get(j));
break;
}
else
{
System.out.println("ce numéro ("+b+") n'existe pas!");
}
break;
}
}
}
Do it simply like this
String str_line= "702345678,714326578,701234567,791234567,751234567";
String[] strArray = str_line.split(",");
String key = "702345678";
for(String v:strArray) {
if(v.equals(key)) {
System.out.println("found");
}
}
I'm not realy sure of what you want, but if you just need the index of b in your array just do this:
public static void main(String [] args) throws IOException{
...
int b = 773214576;
int tmp = list.indexOf(b+"");
if(tmp!=-1) {
System.out.println("Trouvé "+ b + " à l'index " + tmp);
} else {
System.out.println("Ce numéro ("+b+") n'existe pas!");
}
...
}
Another answer, using Guava :
(in this case, there really is no need, you could simply use split() method from String object, but like Guava readibility and returns)
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.google.common.base.Splitter;
public class RegexExample {
String filename = "numbercall.txt";
public boolean isInList(String numberToCheck) throws IOException {
BufferedReader file = loadFile();
for (String number : extractNumberListFrom(file)) {
if (number.trim().equals(numberToCheck)) {
return true;
}
}
return false;
}
private Iterable<String> extractNumberListFrom(BufferedReader buffer) throws IOException {
StringBuilder numberList = new StringBuilder();
String line;
while ((line = buffer.readLine()) != null) {
numberList.append(line);
}
return Splitter.on(",").split(numberList.toString());
}
private BufferedReader loadFile() {
InputStream fstream_school = RegexExample.class.getResourceAsStream(filename);
BufferedReader buffer = new BufferedReader(new InputStreamReader(fstream_school));
return buffer;
}
}