Unable to output ArrayList contents - java

I'm reading a txt file wich contains one word in each line, stripping the word from non-alphanumeric characters and storing the results into an Array List.
public class LeeArchivo
{
public static void main(String args[]) throws IOException
{
try
{
BufferedReader lector = null;
List<String> matrix = new ArrayList<String>();
lector = new BufferedReader(new FileReader("spanish.txt"));
String line = null;
while((line = lector.readLine())!=null)
{
//matrix.add(line);
matrix.add((line.split("[^a-zA-Z0-9']").toString()));
}
System.out.println(matrix);
System.out.println(matrix.size());
} catch (IOException e)
{
e.printStackTrace();
}
}
}
when I try to print the contents of the ArrayList all I get is each String Object's memory address. The funny thing is, if I don't split the line ie.: I just matrix.add(line) I get the Strings Ok.
I've tried StringBuilders, Iterators, .toString but nothing works.
Can somebody help me to understand what's going on here?
Thanks.

The line.split("[^a-zA-Z0-9']") call returns a String array. Not a String.
So, you are adding not a String instance to your array list, but the result of String array object toString() method call - the String array object's memory address.
If you need to get the whole string after splitting, you should concatenate all
elements of the array, for example:
while((line = lector.readLine())!=null) {
String[] arr = line.split("[^a-zA-Z0-9']");
String res = "";
for(String s : arr) {
res += s;
}
matrix.add(res);
}

Related

How to use array instead of arraylist in loading line by line object from file in java

(Homework:) I want to use array instead of arraylist in this situation. I have the arraylist name Employee and i have to insert data of it into the tree. I load data line by line from file. But i want to use array for the Employee not arraylist. How can i do that ? There're any ways to use array instead of arraylist in this situation. The following code is my example code for arraylist Employee. I want to change List to Employee[] how can i write the following function in style of Array.
public static void main(String[] args) {
List<Employee> employees = read("employees.txt");
BST bst = new BST();
for(Employee e : employees){
bst.insert(e);
}
}
public static List<Employee> read(String file) {
try {
List<Employee> employees = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null ){
String[] arr = line.split("-");
Employee emp = new Employee();
emp.ccode = Integer.parseInt(arr[0]);
emp.cus_name = arr[1];
emp.phone = arr[2];
employees.add(emp);
}
return employees;
} catch (IOException ex) {
Logger.getLogger(TestMusic.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
This approach is not the best one, but might solve your problem. to be used for java versions < 8.
The approach is to parse the file to get no. of lines, to create the employee array, and parse again to get data of all the individual employees
public static void main(String[] args) {
int empSize = getNumberOfEmployees("employees.txt");
employees = new Employee[empSize];
employees = read("employees.txt");
BST bst = new BST();
for(Employee e : employees){
bst.insert(e);
}
}
public static int getNumberOfEmployees (String file) {
int totalEmp = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null ) {
totalEmp ++;
}
}catch (IOException e) {
e.printStackTrace();
}
return totalEmp;
}
public static Employee[] read(String file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
int i=0;
while((line = reader.readLine()) != null ){
String[] arr = line.split("-");
Employee emp = new Employee();
emp.ccode = Integer.parseInt(arr[0]);
emp.cus_name = arr[1];
emp.phone = arr[2];
employees[i] = emp;
i++;
}
return employees;
} catch (IOException ex) {
Logger.getLogger(TestMusic.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
Without giving you any code (do it by yourself ;-)):
Parse the file twice:
get the number of lines, create an Array based on the number of lines
parse the file again, fill the Array
And some Research (keywords BufferedReader and Array) would help you too.
It is unclear from your requirements what you want to do in the following situations:
one line fails to parse;
cannot open the file for reading.
Here is a solution which (eww) will just ignore the unparseable entries and return an empty array if the file cannot be parsed:
public final class TestMusic
{
private static final Employee[] NO_EMPLOYEES = new Employee[0];
public static void main(final String... args)
{
final BST bst = new BST();
for (final Employee emp: getArray())
bst.insert(emp);
}
private static Employee toEmployee(final String input)
{
final String[] arr = input.split["-"];
final Employee emp = new Employee();
try {
emp.ccode = Integer.parseInt(arr[0]);
emp.cus_name = arr[1];
emp.phone = arr[2];
return emp;
} catch (NumberFormatException | IndexOutOfBoundsException e) {
return null;
}
}
private static Employee[] getArray()
{
final Path path = Paths.get("employees.txt");
try (
Stream<String> lines = Files.lines(path);
) {
return lines.map(TestMusic::toEmployee)
.filter(Objects::nonNull)
.toArray(Employee[]::new);
} catch (IOException ignored) {
return NO_EMPLOYEES;
}
}
}
Note how this solution does not use an intermediate list at all; instead, it makes use of the Java 8 Stream API.
What is left to do here is to handle errors... That is for you to decide :)
if you want to convert ArrayList to array use the following code:
Employee [] arrayOfEmpolyees = new Employee[employees.size()]
employees.toArray(arrayOfEmpolyees);
That is like doing a step backwards. Java collections (for example the List interface and the ArrayList implementation) have various advantages compared to "plain old" arrays.
The only real advantage of arrays is their reduced overhead - but that is only important when dealing with millions or billions of things to store in a container.
So the real answer is: don't do that. Just keep using List/ArrayList.
But in case you insist, you can of course use arrays - but then you have to add that part that makes ArrayList more convenient: you have to provide code that dynamically "grows" your array once you hit its size limit. That works like this:
you start with an initial array of size 100 for example
while populating that array, you keep track of the number of slots "in use"
when your code wants to add the 101st element, you "grow" the array
Growing works by:
creating a new array, that has like currentArray.length + 100 capacity
using System.arraycopy() to move all entries from the old to the new array
Guess the size of the array, for example by taking the size of the file and dividing by 20 (approximately the size of the line in the example you gave). Then read into the array, counting the lines. If the array is full before you have reached the end of the file, allocate a new array double the size, copy everything from the old array to the new array, replace the old array with the new array and continue the same way until done. You can look at the source of ArrayList to see an example of how it is done - basically this is what ArrayList does internally.

Reading letters and avoiding numbers and symbols

I am given a .txt file which has a bunch of words, here is a sample of what it looks like:
Legs
m%cks
animals
s3nt!m4nts
I need to create a code which reads this .txt file and put the words without numbers and symbols into an array. So basically I gotta put Legs and animals into an array The other two words I gotta just print it out.
public class Readwords {
public static void main(String[] args) {
String[] array=new string[10];
}
}
How do I get the program to read letters only and ignore the numbers and symbols?
You can use Regex for finding numbers and symbols,after that replace them.
1).Read the whole .txt file to a string.
2).Use replaceAll function to replace the unwanted characters.
String str = your text;
str = str.replaceAll(your regex, "");
You can try this:
try {
BufferedReader file = new BufferedReader(new FileReader("yourfile.txt")
String line;
ArrayList<String> array = new ArrayList<String>();
while ((line = file.nextLine()) != null) {
if (line.matches("[a-zA-Z]+"))
array.add(line);
else
System.out.println(line);
}
String[] result = array.toArray(new String[array.size()]);
file.close();
return result;
}
catch (Exception e)
e.printStackTrace;

Null when splitting a string

I need to create my own sort method for an array, and I begin my splitting the text file into an array filled with the words. The file format is: an integer n, followed by n words.
Here's an example: 4 hello hello world hello
However, my array prints: [null4, hello, hello, world, hello]
WHY! I don't understand why there is a null before. And, if I remove the number 4 (which plays no role in my program at the moment) I get: [nullhello, hello, world, hello]
Can you please help me remove this null? Thanks in advance!
public static void main(String[] args) throws FileNotFoundException {
filePath = "***TEXT FILE HERE***";
fileInput = new Scanner(new File(filePath));
convertFile(fileInput);
}
public static void convertFile(Scanner file) {
String line;
while (fileInput.hasNextLine()) {
line = fileInput.nextLine();
fileData = fileData + line;
}
String[] array = createArray(fileData);
System.out.println(Arrays.toString(array));
}
public static String[] createArray(String data) {
String[] dataArray = data.split("\\s+");
return dataArray;
}
You did not initialise the fileData variable before using it.
try
fileData = "";
fileData = fileData + line;
this is not the best choise for building a string... try to replace it with a StringBuilder
StringBuilder fileData = new StringBuilder(); // to instantiate
fileData.append(line + "\n"); // to add lines
String finalString = fileData.toString(); // to build the string
for larger strings your method of concatenation will become very slow

Reading and returning multiple bin files

private static int count = 0;
public static String[] play()throws Exception{
File file=new File("E:/proj/"+count+".bin");
FileInputStream fin=new FileInputStream("E:/proj/"+count+".bin");
//reading the byte content of the bin files
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//storing the deserialized object that is returned to an object.
Object obj=serializer.toObject(fileContent);
//converting the obtained object to string
String word=obj.toString();
String[] args=new String[]{word};
count++;
return args ;
}
This snippet was actually supposed to read all the bin files present in that specified path and eventually convert it to string and store all the byte[] converted to strings as different string elements in a string[] return the string[]. Though it reads all the bin files owing to the counter, somehow, it returns only string of the 1st binary file it reads.
Even this modified version dosent seem to work. I guess it reads all the bin files, but returns only the string of the last bin file read. What i was trying out for was, to store all the string elements to the string[] and return the string[] to another calling function.
public static String[] play(){
int i = 1;
String[] args=null;;
String result = null;
while (true) {
try {
result += processFile(i++);
args=new String[]{result};
}
catch (Exception e) {
System.out.println("No more files");
break;
}
}
return args;
}
private static String processFile(int fileNumber) throws Exception {
File file=new File("E:/proj/"+fileNumber+".bin");
FileInputStream fin=new FileInputStream("E:/proj/"+fileNumber+".bin");
//reading the byte content of the bin files
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//storing the deserialized object that is returned, to an object.
Object obj=serializer.toObject(fileContent);
//converting the obtained object to string
String word=obj.toString();
return word;
}
If I understand your requirement clearly, you may try changing your code this way:
List<String> args = new ArrayList<String>();
while (true) {
try {
args.add(processFile(i++));
}
catch (Exception e) {
// your code
}
}
String[] array = args.toArray(new String[0]);
There are several problems in the code you just posted:
- result is initialised to null so your code will throw a NPE in the first loop.
- assuming you initialise it properly (in your case to ""), args is reallocated to a new array on each loop so you lose the information you got from the previous loop.
If you want your play() method to return an array, where each item in the array is the content of one file, this should work. If you want something different you need to explain your requirement more clearly.
public static String[] play() {
int i = 1;
List<String> files = new ArrayList<String>();
while (true) {
try {
files.add(processFile(i++));
} catch (Exception e) {
System.out.println("No more files");
break;
}
}
return files.toArray(new String[0]);
}

Read each line in a text file for strings, doubles, and ints an place them in different arrays

this is my first question here so I hope I'm doing this right. I have a programming project that needs to read each line of a tab delimited text file and extract a string, double values, and int values. I'm trying to place these into separate arrays so that I can use them as parameters. This is what I have so far(aside from my methods):
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class LoanDriver {
public static void main(String[] args)
{
String[] stringData = new String[9];
Scanner strings = null;
try
{
FileReader read = new FileReader("amounts.txt");//Read text file.
strings = new Scanner(read);
String skip = strings.nextLine();//Skip the first line by storing it in an uncalled variable
strings.useDelimiter("\t *");//Tab delimited
}
catch (FileNotFoundException error)
{}
while (strings.hasNext())
{
String readLine = strings.next();
stringData = readLine.split("\t");
}
}}
If I try to get the [0] value, it skips all the way to the bottom of the file and returns that value, so it works to some extent, but not from the top like it should. Also, I can't incorporate arrays into it because I always get an error that String[] and String is a type mismatch.
Instead of using delimiter, try reading the file line by line using Scanner.nextLine and split each new line you read using String.split ("\t" as argument).
try {
FileReader read = new FileReader("amounts.txt");//Read text file.
strings = new Scanner(read);
String skip = strings.nextLine();//Skip the first line by storing it in an uncalled variable
}
catch (FileNotFoundException error) { }
String line;
while ((line = strings.nextLine()) != null) {
String[] parts = line.split("\t");
//...
}
You are getting the last value in the file when you grab stringData[0] because you overwrite stringData each time you go through the while loop. So the last value is the only one present in the array at the end. Try this instead:
List<String> values = new ArrayList<String>();
while (strings.hasNext()) {
values.add(strings.next());
}
stringData = values.toArray(new String[values.size()]);

Categories