Regular Expression..Splitting a string array twice - java

I have a text file with state-city values:-
These are the contents in my file:-
Madhya Pradesh-Bhopal
Goa-Bicholim
Andhra Pradesh-Guntur
I want to split the state and the city... Here is my code
FileInputStream fis= new FileInputStream("StateCityDetails.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
int h=0;
String s;
String[] str=null;
byte[] b= new byte[1024];
while((h=bis.read(b))!=-1){
s= new String(b,0,h);
str= s.split("-");
}
for(int i=0; i<str.length;i++){
System.out.println(str[1]); ------> the value at 1 is Bhopal Goa
}
}
Also I have a space between Madhya Pradesh..
So i want to Remove spaces between the states in the file and also split the state and city and obtain this result:-
str[0]----> MadhyaPradesh
str[1]----> Bhopal
str[2]-----> Goa
str[3]----->Bicholim
Please Help..Thank you in advance :)

I would use a BufferedReader here, rather than the way you are doing it. The code snippet below reads each line, split on hyphen (-), and removes all whitespace from each part. Each component is entered into a list, in left to right (and top to bottom) order. The list is converted to an array at the end in case you need this.
List<String> names = new ArrayList<String>();
BufferedReader br = null;
try {
String currLine;
br = new BufferedReader(new FileReader("StateCityDetails.txt"));
while ((currLine = br.readLine()) != null) {
String[] parts = currLine.split("-");
for (int i=0; i < parts.length; ++i) {
names.add(parts[i].replaceAll(" ", ""));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// convert the List to an array of String (if you require it)
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);
// print out result
for (String val : nameArr) {
System.out.println(val);
}

Related

reading file line by line and adding lines to array

I want to read a file line by line in Java. Each line is added as an item to an array. Problem is that, I have to create the array based on the number of lines in the file while I am reading line by line.
I can use two separate while loops one for counting and then creating the array and then adding items. But it is not efficient for large files.
try (BufferedReader br = new BufferedReader(new FileReader(convertedFile))) {
String line = "";
int maxRows = 0;
while ((line = br.readLine()) != null) {
String [] str = line.split(" ");
maxColumns = str.length;
theRows[ maxRows ] = new OneRow( maxColumns ); // ERROR
theRows[ maxRows ].add( str );
++maxRows;
}
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
Consider private OneRow [] theRows; and OneRow is defined as String []. the file looks like
Item1 Item2 Item3 ...
2,3 4n 2.2n
3,21 AF AF
...
You can't resize an array. Use the ArrayList class instead:
private ArrayList<OneRow> theRows;
...
theRows.add(new OneRow(maxColumns));
Check ArrayList. ArrayList is resisable array.And is equivalent to C++ Vector.
try (BufferedReader br = new BufferedReader(new FileReader(convertedFile)))
{
List<String> str= new ArrayList<>();
String line = "";
while ((line = br.readLine()) != null) {
str.add(line.split(" "));
}
}
catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e){
System.out.println(e.getMessage());
}
I would consider using the ArrayList data structure. If you are unfamiliar with how ArrayLists work I would read up on the documentation.

java read only integers from file

If I have a file that contains for example:
results1: 2, 4, 5, 6, 7, 8, 9
results2: 5, 3, 7, 2, 8, 5, 2
I want to add the integers from each line to a array. One array
for each line. How can I do this with code that does only read the integers?
Here's what I got this far
String data = null;
try {
Scanner in = new Scanner(new File(myFile));
while (in.hasNextLine()) {
data = in.nextLine();
numbers.add(data);
}
in.close();
} catch (Exception e) {
}
Easy.
One line per array, not two as you have it. New line after each one.
Read each line as a String, discard the leading "resultsX:", and split what remains at a delimiter of your choosing (e.g. comma). Parse each into an integer and add it to a List.
I don't think that leading "results1: " is adding any value. Why do you have that?
public static void main(String[] args) throws IOException {
BufferedReader reader=null;
try {
reader = new BufferedReader(new FileReader(new File("PATH TO FILE")));
// Only works if File allways contains at least two lines ... all lines after the second
// will be ignored
System.out.println(String.format("Array 1 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
System.out.println(String.format("Array 2 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
} finally {
if (reader!=null) {
reader.close();
}
}
}
private static Integer[] stringArray2IntArray(String[] numStrings) {
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < numStrings.length; i++) {
result.add(Integer.parseInt(numStrings[i].trim()));
}
return result.toArray(new Integer[numStrings.length]);
}
private static String[] readNextLine(BufferedReader reader) throws IOException {
return reader.readLine().split(":")[1].split(",");
}
Assuming you have an input file, like this:
2,4,5,6,7,8,9
5,3,7,2,8,5,2
here is a code snippet to load it:
String firstLine = "";
String secondLine = "";
File file = new File("path/to/file");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
firstLine = br.readLine();
secondLine = br.readLine();
} catch(Exception e){
e.printStackTrace();
}
String[] firstResult = firstLine.split(",");
String[] secondResult = secondLine.split(",");
int[] firstIntegers = new int[firstResult.length];
for(int i = 0; i <= firstResult.length ; i++){
firstIntegers[i] = Integer.parseInt(firstResult[i]);
}
int[] secondIntegers = new int[secondResult.length];
for(int i = 0; i <= secondResult.length ; i++){
firstIntegers[i] = Integer.parseInt(secondResult[i]);
}
Open the file with a BufferedReader br and then read it line by line.
Store each line in an int array and add all those int arrays to a list. At the end, this list will contain all the int arrays that we wanted, so iterate this list to do whatever you want to do next.
String filePath = "/path/to/file";
BufferedReader br = null;
List<Integer[]> arrays = new ArrayList<>(); //this contains all the arrays that you want
try {
br = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = br.readLine()) != null) {
line = line.substring(line.indexOf(":")+2); //this starts the line from the first number
String[] stringArray = line.split(", ");
Integer[] array = new Integer[stringArray.length];
for (int i = 0; i < stringArray.length; ++i) {
array[i] = Integer.parseInt(stringArray[i]);
}
arrays.add(array);
}
} catch (FileNotFoundException ex) {
System.err.println(ex);
} catch (IOException ex) {
System.err.println(ex);
} finally {
try {
br.close();
} catch (Exception ex) {
System.err.println(ex);
}
}
Since ArrayLists keep insertion order, then, e.g., arrays.get(3) will give you the array of the fourth line (if there is such a line) and arrays.size() will give you the number of lines (i.e., int arrays) that are stored.

Java read large text file with separator

I'm trying to read a large text file in the form of:
datadfqsjmqfqs+dataqfsdqjsdgjheqf+qsdfklmhvqziolkdsfnqsdfmqdsnfqsdf+qsjfqsdfmsqdjkgfqdsfqdfsqdfqdfssdqdsfqdfsqdsfqdfsqdfs+qsfddkmgqjshfdfhsqdflmlkqsdfqdqdf+
I want to read this string in the text file as one big java String. Is this possible? I know the use of the split method.
It worked to read it line by line, but what I really need is to split this long text-string at the '+' sign. Afterwards I want to store it as an array, arraylist, list,...
Can anyone help me with this? Because every information on the internet is just about reading a file line by line.
Thanks in advance!
String inpStr = "datadfqsjmqfqs+dataqfsdqjsdgjheqf+qsdfklmhvqziolkdsfnqsdfmqdsnfqsdf+qsjfqsdfmsqdjkgfqdsfqdfsqdfqdfssdqdsfqdfsqdsfqdfsqdfs+qsfddkmgqjshfdfhsqdflmlkqsdfqdqdf+";
String[] inpStrArr = inpStr.split("+");
Hope this is what you need.
You can read file using BufferedReader or any IO-classes.suppose you have that String in testing.txt file then by reading each line from file you can split it by separator (+). and iterate over array and print.
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));//file name with path
while ((sCurrentLine = br.readLine()) != null) {
String[] strArr = sCurrentLine.split("\\+");
for(String str:strArr){
System.out.println(str);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
It seems to me like your problem is that you don't want to read the file line by line. So instead, try reading it in parts (say 20 characters each time and building your string):
char[] c = new char[20]; //best to save 20 as a final static somewhere
ArrayList<String> strings = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(filename));
while (br.read(c) == 20) {
String str = new String(c);
if (str.contains("+") {
String[] parts = str.split("\\+");
sb.append(parts[0]);
strings.add(sb.toString());
//init new StringBuilder:
sb = new StringBuilder();
sb.add(parts[1]);
} else {
sb.append(str);
}
}
You should be able to get a String of length Integer.MAX_VALUE (always 2147483647 (231 - 1) by the Java specification, the maximum size of an array, which the String class uses for internal storage) or half your maximum heap size (since each character is two bytes), whichever is smaller
How many characters can a Java String have?
Try this one:
private static void readLongString(File file){
ArrayList<String> list = new ArrayList<String>();
StringBuilder builder = new StringBuilder();
int r;
try{
InputStream in = new FileInputStream(file);
Reader reader = new InputStreamReader(in);
while ((r = reader.read()) != -1) {
if(r=='+'){
list.add(builder.toString());
builder = new StringBuilder();
}
builder.append(r);
}
}catch (IOException ex){
ex.printStackTrace();
}
for(String a: list){
System.out.println(a);
}
}
Here is one way, caveat being you can't load more than the max int size (roughly one GB)
FileReader fr=null;
try {
File f=new File("your_file_path");
fr=new FileReader(f);
char[] chars=new char[(int)f.length()];
fr.read(chars);
String s=new String(chars);
//parse your string here
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fr!=null){
try {
fr.close();
} catch (IOException e) {
}
}
}

To print the given rows of string into columns

I have *.txt file with first row as name,address,mail id and second line with the values. I have to print this into two columns,the first one with the headings and second with the value using Java. how do I do this?
public class ReadFile1 {
public static void main(String[] args) {
BufferedReader br=null;
String sCurrentLine = null;
String delimiter = ",";
String[] filetags;
try {
br = new BufferedReader(new FileReader("path\\Read.txt"));
sCurrentLine = br.readLine();
StringBuffer result = new StringBuffer();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
filetags = line.split(delimiter);
for(int i = 0;i < line.length(); i++)
{
System.out.println("****" +sCurrentLine);
String[] s = line.split(",");
for(int j = i-1; j<line.length();j++)
{
System.out.println("##############"+Arrays.toString(s));
}
}
}
}
This is what I tried. Ex: I have a file say,
line1) name,email,mobile and second
line2) john,j#abc.com,9876
line3) max,max#xyz.com,1234
Now, I need to print:
name john
email john#abc.com
moblie 9876
name max
email max#xyz.com
mobile 1234
Below is one way you may be able to get what you want, It is similar to how you have attempted but slightly more refined.
The File:
name,email,mobile and second
john,j#abc.com,9876
max,max#xyz.com,1234
The code:
//File is on my Desktop
Path myFile = Paths.get(System.getProperty("user.home")).resolve("Desktop").resolve("tester.txt");
//Try-With-Resources so we autoclose the reader after try block
try(BufferedReader reader = new BufferedReader(new FileReader(myFile.toFile()))){
String[] headings = reader.readLine().split(",");//Reads First line and gets headings
String line;
while((line = reader.readLine()) != null){//While there are more lines
String[] values = line.split(","); //Get the values
for(int i = 0; i < values.length; i++){//For each value
System.out.println(headings[i] + ": " + values[i]);//Print with a heading
}
}
} catch (IOException io) {
io.printStackTrace();
}
Good Luck!
Something like this should do the trick.
Read the file and store each line in a list.
Iterate through the list of lines
If it is safe to assume the first line will always be the title line, take the input and store it in a collection.
For the rest of the lines, split on the comma and use the index of the splitter array to refer to the title column.
List <String> lines = new ArrayList<String>();
Scanner scanner = new Scanner(new File("FileName.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
lines.add(line);
}
scanner.close();
int lineNo = 0;
List <String> title = new ArrayList<String>();
for(String line : lines){
if(lineNo == 0){
String [] titles = line.split(",");
for(String t : titles){
title.add(t);
}
lineNo++;
}
else{
String input = line.split(",");
for(int i = 0; i<input.length; i++){
System.out.println(title.get(i) + ": " + input[i]);
}
lineNo++;
}
}

How to split a fraction into two Integers?

I'm working on a program where I need to create an object list from an external file containing fractions. I need to separate the numerator and denominator into two separate integers, without having the "/" be involved.
This is what I have so far:
while (fractionFile.hasNextLine()){
num.add(fractionFile.nextInt());
den.add(fractionFile.nextInt());
}
I can't figure out how to have num.add read up until the "/" and have den.add read right after the "/"
Any help would be much appreciated.
String fraction="1/2";
String []part=fraction.split("/");
num.add(part[0])
den.add(part[1])
Use String class split method to split the string using the desired pattern.
BufferedReader br = null;
Integer num = 0;
Integer den = 0;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("test"));
while ((sCurrentLine = br.readLine()) != null) {
String [] str = sCurrentLine.split("/");
if(str.length>2)throw new IllegalArgumentException("Not valid fraction...");
num = num+Integer.parseInt(str[0]);
den = den+Integer.parseInt(str[1]);
}
System.out.println(num);
System.out.println(den);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
while (fractionFile.hasNextLine()){
//If file contains
// 1/2
// 2/4
// 5/6
String line = fractionFile.nextLine();
String split[]=line.split("/");
num.add(Integer.parseInt(split[0])); // 1 stored in num
den.add(Integer.parseInt(split[1])); // 2 stored in den
}
Assuming that you have multiple fractions in your file seperated by a token (e.g. line brake, or ;):
String input = "1/2;3/4;5/6";
String token = ";"
String[] currentFraction = null;
final List<Integer> nums = new LinkedList<>();
final List<Integer> denoms = new LinkedList<>();
for (String s : input.split(token)) {
currentFraction = s.split("/");
if (currentFraction.length != 2)
continue;
nums.add(Integer.parseInt(currentFraction[0]));
denoms.add(Integer.parseInt(currentFraction[1]));
}

Categories