tokenized output into an array from string - java

i am working on netbeans...i need to read a file and tokenize then and store it in an array for my future operations....i have attached the code where the line5 contains the tokens...while converting into array iam getting error as
Exception :
" Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1000
at preprocess.mainpage.jButton2ActionPerformed(mainpage.java:224)
at preprocess.mainpage.access$100(mainpage.java:18)
at preprocess.mainpage$2.actionPerformed(mainpage.java:62)"
Code:
int counter=-1;
int n=0;
String[] arr = new String[1000];
try
{
BufferedReader b = new BufferedReader(new FileReader("C:/Users/sky/Documents/NetBeansProjects/Preprocess/src/preprocess/cdr1.txt"));
String line;
while ((line = b.readLine()) != null)
{
counter+=1;
StringTokenizer st2 = new StringTokenizer(line, " ");
String line5 = (String) st2.nextElement();
arr[n] = line5;
n++;
}
}
catch (Exception e)
{
}

ArrayIndexOutOfBoundsException because may be your array size is less. So better use ArrayList like following:
int counter=-1;
int n=0;
//String[] arr = new String[1000];
List<String> list = new ArrayList<String>(); // Create ArrayList
try{
BufferedReader b = new BufferedReader(new FileReader("C:/Users/sky/Documents/NetBeansProjects/Preprocess/src/preprocess/cdr1.txt"));
String line;
while ((line = b.readLine()) != null) {
counter+=1;
StringTokenizer st2 = new StringTokenizer(line, " ");
String line5 = (String) st2.nextElement();
//arr[n] = line5;
//n++;
list.add(line5); // Add you string into list
}
String[] aa = list.toArray(new String[0]); // convert list into String of array if you need it
}
catch (Exception e){
}

Related

incompatible types: String[] cannot be converted to String

I'm being completely beaten up by types in Java.
I have coordinates in a txt file, which ultimately I want to format into an array of these co-ordinates, with each array item being a double.
Each line of my txt file looks like so:
13.716 , 6.576600074768066
Currently, I'm trying to split this line into an array of two Strings, which I will then try and parse into doubles, but I keep getting the error in the title. Where am I going wrong?
Any other better approaches on converting my Arraylist of Strings to a formatted list of double coordinates would be great, like so
[[0,1], [0,2], 0,4]
Code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
for (int i=0; i < data.size(); i++){
data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
The split(",") method return array of string string[] and you can't set string by array of string.
Crate point class with let lan double variabels and then create array of this point and them fill them with data from reading each line:
class Point{
double lat;
double len;
Point(double lat, double len){
this.lat = lat;
this.len = len;
}
}
And then use this class in your code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
List<Point> points = new ArrayList<Point>();
for (int i=0; i < data.size(); i++){
double lat = Double.parseDouble(data.get(i).split(",")[0]);
double len = Double.parseDouble(data.get(i).split(",")[1]);
points.add(new Point(lat, len));
//data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
you can update your while loop like this
while ((line = reader.readLine()) != null) {
String[] splits = line.split(",");
for(String s : splits) {
data.add(s);
}
}

Text File Reading Error with multiple delimiter JAVA

This is the text file I want to read and display on console. Here are my codes for reading the file:
public class CarMain
{
public static void main (String args[]) throws IOException
{
try
{
File f = new File("Cars.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = "", fullName;
String[] arrName = null;
Car[] c = new Car[3];
String name, ic, manufacturer, model;
int num = 0;
while ((line = br.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line);
name = st.nextToken();
StringTokenizer st2 = new StringTokenizer(line,"://;");
ic = st2.nextToken();
manufacturer = st2.nextToken();
model = st2.nextToken();
c[num] = new Car(name,ic, manufacturer, model);
num++;
}
br.close();
fr.close();
for (int i = 0; i < c.length; i++)
{
System.out.println(c[i].toString());
}
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,"error opening file");
}
}
}
then I get this output:
It seems that it doesn't display the model name after ";" and the data is not in the right place.
My expected output is like this:
Name: Fatimah Zahra Ali
IC: 860802105012
Manufacturer: Proton
Model: Perdana
.
.
.
Please help. Thank you.
Your st2 is a new tokenizer. You should read the tokens from st2 as follows:
StringTokenizer st2 = new StringTokenizer(line,"://;");
name = st2.nextToken(); // first token
ic = st2.nextToken(); // second
manufacturer = st2.nextToken(); // third
model = st2.nextToken(); // fourth
The first tokenizer is not required.
I have put all st2 but the name is missing.

Array/Loop does not output primary line

I'm having a small problem with my code and I'm not exactly sure how to fix it.. Basically I'm trying to separate the file into different lines (Frames) and then input those lines into the file, and proceed to print them. My first line of the file never prints.
public class Main {
public static void main(String[] args) throws IOException
{
/*Switch switcherino = new Switch();*/
Frame frame = new Frame();
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to process: ");
String fileName = input.nextLine();
FileInputStream inputStream =
new FileInputStream(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream,Charset.forName("UTF-8"));
BufferedReader bufferedReader =
new BufferedReader(inputStreamReader);
try{
String str = " ";
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
}
catch (IOException e){
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
I don't want to use an ArrayList, as much as it would probably be easier.
Thanks in advance!
File: (switch.txt)
fa00 123123123abc 111111222222 data1
fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5
Output: (from System.println(words[i]);)
fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5
This is wrong logic: you read the line, you split it into words so then go ahead and print them - no need to try and read any more lines
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
use this instead
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
System.out.println(words[i]);
}
}
// to count length
int length = 0;
BufferedReader br =
new BufferedReader(inputStreamReader);
while(true){
str = br.readLine();
if(str == null) break;
else length++;
} // this loop counts the length!!
final int clength = length;
//now this is what you want!
String words[] = new String[clength];
int j= 0;
while(true){
str = bufferedReader.readLine();
if(str == null) break;
words[j++] = str;
System.out.println(str); //FIXED
}
//Now the words[] have all the lines individually
Your code doesn't work because you called readLine() twice, which skipped the first line. Try this and let me know.
You don't need to use split() since you want the entire line :)
while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");
for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
When iterate the file, you split your first line into a String array,
words[] contains the following elements : fa00, 123123123abc, 111111222222 and data1.
and then the inner for loop iterate your bufferReader and you assign the lines to a specific index of word and then you print out the word array elements
You are not supposed to invoke bufferedReader.readLine() in the inner for loop, it breaks your logic.

How to split text file based on startswith

I want to split file as Header with detail in a list based on sequence.
want to split the text file using Header and detail I tried something like this but doesn't help.
I wanted to call previous iteration of iterator but I couldn't...
File :
H>>>>>>
L>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>> ...
I wanted :
List 1 with H , L , L ,L
List 2 with H , L , L
List 3 with H , L
Code Tried :
List<String> poString = new ArrayList<String>();
if(poString !=null && poString.size() > 0)
{
ListIterator<String> iter = poString.listIterator();
while(iter.hasNext())
{
String tempHead = iter.next();
List<String> detailLst = new ArrayList<String>();
if(tempHead.startsWith("H"))
{
while(iter.hasNext())
{
String detailt = iter.next();
if(!detailt.startsWith("H"))
detailLst.add(detailt);
else
{
iter.previousIndex();
}
}
}
}
Try this (untested):
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
List<StringBuilder> myList = new List<StringBuilder>();
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line[0] == 'H')
{
myList.add(sb);
sb = new StringBuilder();
}
sb.append(line[0]);
line = br.readLine();
}
} finally {
br.close();
}
as far as I understood, eventually how many H..lines in your file, how many List<String> would you want to have.
If you don't know the exact number, (in your example, it is 3) then you have a List of List (List<List<String>>).
//read the file, omitted
List<List<String>> myList = new ArrayList<<List<String>>();
List<String> lines = null;
boolean createList = false;
while (line != null) {
if (line.startsWith("H")){
myList.add(lines);
lines = new ArrayList<String>();
}
//if the 1st line of your file not starting with 'H', NPE, you have to handle it
lines.add(line);
line=readnextlineSomeHow(); //read next line
}
the above codes may not work out of box, but it gives you the idea.
Try this, I've tried a little on my own and it works
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
ArrayList<ArrayList<String>> result = new ArrayList<> ();
int numlines =0;
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line.startsWith("H"))
{
result.add(new ArrayList<String>());
result.get(numlines).add("H");
line = br.readLine();
while(line != null && !line.startsWith("H")){
if(line.startsWith("L")) result.get(numlines).add("L");
line = br.readLine();
}
++numlines;
}
else line = br.readLine();
}
} finally {
br.close();
}
You can use this..
public static void main(String a[]) throws Exception
{
ArrayList<String> headers=new ArrayList();
ArrayList<String> lines=new ArrayList();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
File f= new File("inputfile.txt");
Scanner scanner = new Scanner(f);
try {
while (scanner.hasNextLine()){
String ss=scanner.nextLine();
String key= String.valueOf(ss.charAt(0));
if ( map.containsKey(key))
{
ArrayList<String> temp=(ArrayList) map.get(key);
temp.add(ss);
map.put(key, temp);
}
else
{
ArrayList<String> temp= new ArrayList();
temp.add(ss);
map.put(key, temp);
}
}
}
catch(Exception e)
{
throw e;
}
}

skip inserting first line of csv file

I have a method that takes data from a .csv file and puts it into an array backwards
(first row goes in last array slot) however I would like the first row in the .csv file to not be in the array. How would I accomplish this? Here is my code thus far:
public static String[][] parse(String symbol) throws Exception{
String destination = "C:/"+symbol+"_table.csv";
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(destination)));
lnr.skip(Long.MAX_VALUE);
String[][] stock_array = new String[lnr.getLineNumber()][3];
try{
BufferedReader br = new BufferedReader(new FileReader(destination));
String strLine = "";
StringTokenizer st = null;
int line = lnr.getLineNumber()-1;
while((strLine = br.readLine()) != null){
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
stock_array[line][0] = st.nextToken();
st.nextToken();
stock_array[line][1] = st.nextToken();
stock_array[line][2] = st.nextToken();
st.nextToken();
st.nextToken();
st.nextToken();
}
line--;
}
}
catch(Exception e){
System.out.println("Error while reading csv file: " + e);
}
return stock_array;
}
You can skip the first line by just reading it in and doing nothing. Do this just before your while loop:
br.readLine();
To make sure that your array is the right size and lines get stored in the right places, you should also make these changes:
String[][] stock_array = new String[lnr.getLineNumber()-1][3];
...
int line = lnr.getLineNumber()-2;
Your code is not efficient, as far as my knowledge goes. Also, you are using linenumberreader.skip(long.max_value), which is not a correct/confirmed way to find the line count of the file. StringTokenizer is kind of deprecated way of splitting tokens. I would code it, in the following way:
public static List<String[]> parse(String symbol) throws Exception {
String destination = "C:/"+symbol+"_table.csv";
List<String[]> lines = new ArrayList<String[]>();
try{
BufferedReader br = new BufferedReader(new FileReader(destination));
int index = 0;
while((line = br.readLine()) != null){
if(index == 0) {
index++;
continue; //skip first line
}
lines.add(line.split(","));
}
if(lines != null && !lines.isEmpty()) {
Collections.reverse(lines);
}
} catch(IOException ioe){
//IOException Handling
} catch(Exception e){
//Exception Handling
}
return lines;
}

Categories

Resources