Change from ArrayList to Array of Strings Java - java

I have this java method which returns an ArrayList, but I want to return an Array of Strings. The method reads the file words.txt (contains all words with a word on each line), and I want to store those words into an Array of Strings.
Heres the code I already have:
public static ArrayList<String> readFile(){
File myFile=new File("./src/folder/words.txt");
Scanner s1=null;
//Creates ArrayList to store each String aux
ArrayList<String> myWords = new ArrayList<String>();
try {
s1 = new Scanner(myFile);
}catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
while(s1.hasNext()){
String aux=s1.next();
System.out.println(aux);
}
s1.close();
return myWords;
}
Can I change this code to return a String []?

You can call List.toArray(String[]) to convert the List<String> to a String[]. I would also prefer a try-with-resources over explicitly closing the Scanner and a List<String> interface. Something like,
public static String[] readFile() { // <-- You could pass File myFile here
File myFile = new File("./src/folder/words.txt");
// Creates ArrayList to store each String aux
List<String> myWords = new ArrayList<>();
try (Scanner s1 = new Scanner(myFile)) {
while (s1.hasNext()) {
String aux = s1.next();
System.out.println(aux);
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
}
return myWords.toArray(new String[0]);
}

try using a built in function of collections class .
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("x");
stringList.add("y");
stringList.add("z");
stringList.add("a");
/*ArrayList to Array Conversion */
/*You can use the toArray method of the collections class and pass the new String array object in the constructor while making a new String array*/
String stringArray[]=stringList.toArray(new String[stringList.size()]);
for(String k: stringArray)
{
System.out.println(k);
}

Add this at last:
String [] arr = myWords.toArray(new String[myWords.size()]);
return arr;
Or simply,
return myWords.toArray(new String[myWords.size()]);

Related

How to populate Array of Strings from text file

I'm trying to get the information from Stock.txt and to transfer it into an array of strings, each index being a new line in the file. I get a warning:
Duplicate local variable. What is the problem, is it out of scope?
public static List<String> getStock(List<String> stockText){
Scanner scanner = null;
try {
File input = new File("Stock.txt");
scanner = new Scanner(input);
String[] info = null;
while (scanner.hasNextLine()) {
info = scanner.nextLine().split(",");
}
List<String> stockText = Arrays.asList(info);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
finally {
scanner.close();
}
return stockText;
}
}
As it is, stockText is an argument and later you create a variable with the same name. That's not allowed. If your intention was to use the same variable, remove List<String> from List<String> stockText = Arrays.asList(info);
Otherwise, give the variable another name.

Reading a text file (~90,000 words) and trying to add each word into an ArrayList of strings

My method read and prints the file, but I am having trouble adding each word to the ArrayList dict.
The reader reads the file one char at a time, so what I have written adds each char to dict: [c,a,t,d,o,g] when I want [cat,dog]. The text file has the words on their own line; how can I distinguish them?
My code so far:
public static List Dictionary() {
ArrayList <String> dict = new ArrayList <String>();
File inFile = new File("C:/Users/Aidan/Desktop/fua.txt");
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
dict.add((char) ch + "");
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
ins.close();
} catch (Exception e) {
}
}
return dict;
}
Please observe Java naming conventions, so readDictionary instead of Dictionary (which looks like a class name). Next, I would pass the fileName into the method (instead of hard-coding the path in your method). Instead of reinventing the wheel, I would use a Scanner. You can also use the try-with-resources instead of finally here (and the diamond operator). Like,
public static List<String> readDictionary(String fileName) {
List<String> dict = new ArrayList<>();
try (Scanner scan = new Scanner(new File(fileName))) {
while (scan.hasNext()) {
dict.add(scan.next());
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
return dict;
}
Alternatively, use a BufferedReader and split each word yourself. Like,
public static List<String> readDictionary(String fileName) {
List<String> dict = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(
new File(fileName)))) {
String line;
while ((line = br.readLine()) != null) {
if (!line.isEmpty()) {
Stream.of(line.split("\\s+"))
.forEachOrdered(word -> dict.add(word));
}
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
return dict;
}
But that is basically what the first example does.
Check out the answer here which shows how to use Scanner to get words from a file: Read next word in java.
Instead of printing out the words, you'd want to append them to an ArrayList.
As the read method of the FileReader can only read a single character at a time and that's not what you want, then I would suggest you use a Scanner to read the file.
ArrayList<String> dict = new ArrayList<>();
Scanner scanner = new Scanner(new File("C:/Users/Aidan/Desktop/fua.txt"));
while(scanner.hasNext()){
dict.add(scanner.next());
}
You can wrap your FileReader in a BufferedReader, which has a readLine() method that will get you an entire line (word) at a time. readLine() returns null when there are no more lines to read.

Reading text into an ArrayList

I have the following data stored in a .txt file:
one,1
two,2
three,3
......
I want to store the information in an array with the following structure:
[one,1,two,2....]
Here is my code so far:
public Shortener( String inAbbreviationsFilePath ) throws FileNotFoundException {
Scanner s = new Scanner(new File(inAbbreviationsFilePath));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
abbreviations = list.toArray(new String[list.size()]);
s.close();
}
My problem is that I cant get the array to be stored so that one and 1 are in different positions. i.e at the moment the array is structured like this [one1,two2,...].
Thanks for help in advance
You have to split each line by the coma and add two parts of it to your result list:
public Shortener( String inAbbreviationsFilePath ) throws FileNotFoundException {
Scanner s = new Scanner(new File(inAbbreviationsFilePath));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()) {
//HERE
String line = s.next();
String[] lineSplit = line.split(","); //split into two tokens
list.add(lineSplit[0]); //word
list.add(lineSplit[1]); //number
}
abbreviations = list.toArray(new String[list.size()]);
s.close();
}
Use this instead of your while loop,
String str;
String []st;
while ((str=s.nextLine())!=null){
st=str.split(",");
list.add(st[0]);
list.add(st[1]);
}
try this
Scanner s = new Scanner(new File...
s.useDelimiter("\\s+|,");

Unable to output ArrayList contents

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);
}

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]);
}

Categories