How to populate Array of Strings from text file - java

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.

Related

Scanning integer and string from file in Java

I'm new to Java and I have to read from a file, and then convert what I have read into variables. My file consists of a fruit, then a price and it has a long list of this. The file looks like this:
Bananas,4
Apples,5
Strawberry,8
...
Kiwi,3
So far I have created two variables(double price and String name), then set up a scanner that reads from the file.
public void read_file(){
try{
fruits = new Scanner(new File("fruits.txt"));
print_file();
}
catch(Exception e){
System.out.printf("Could not find file\n");
}
}
public void print_file(){
while(fruits.hasNextLine()){
String a = fruits.nextLine();
System.out.printf("%s\n", a);
return;
}
}
Currently I am only able to print out the entire line. But I was wondering how I could break this up to be able to store the lines into variables.
So your string a has an entire line like Apples,5. So try to split it by comma and store it into variables.
String arr[] = a.split(",");
String name = arr[0];
int number = Integer.parseInt(arr[1]);
Or if prices are not integers, then,
double number = Double.parseDouble(arr[1]);
Using java 8 stream and improved file reading capabilities you can do it as follows. it stores item and count as key value pair in a map. It is easy to access by key afterwards.
I know this Maybe too advance but eventually this will help you later when getting to know new stuff in java.
try (Stream<String> stream = Files.lines(Paths.get("src/test/resources/items.txt"))) {
Map<String, Integer> itemMap = stream.map(s -> s.split(","))
.collect(toMap(a -> a[0], a -> Integer.valueOf(a[1])));
System.out.println(itemMap);
} catch (IOException e) {
e.printStackTrace();
}
output
{Apples=5, Kiwi=3, Bananas=4, Strawberry=8}
You can specify a delimiter for the scanner by calling the useDelimiter method, like:
public static void main(String[] args) {
String str = "Bananas,4\n" + "Apples,5\n" + "Strawberry,8\n";
try (Scanner sc = new Scanner(str).useDelimiter(",|\n")) {
while (sc.hasNext()) {
String fruit = sc.next();
int price = sc.nextInt();
System.out.printf("%s,%d\n", fruit, price);
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"C://Test/myfile.txt")); //Your file location
String line = reader.readLine(); //reading the line
while(line!=null){
if(line!=null && line.contains(",")){
String[] data = line.split(",");
System.out.println("Fruit:: "+data[0]+" Count:: "+Integer.parseInt(data[1]));
}
//going over to next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Change from ArrayList to Array of Strings 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()]);

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 from a text file with spaces and then putting into arrayList

I have spent the last week trying to figure out how to make this stupid code work. I have managed to get everything to work except for reading from my text file. It can read an individual integer on a line, but when given a line with multiple integers separated by spaces, it freaks out. Now I've gone and tried to fix it and the code won't even compile anymore. Only one line is causing problems.
I'm not good at coding, so I don't know where to begin. Yes, I've looked this up online. Yes, I've checked the forums. Yes, I have tried multiple different methods to make this work....
How do I fix this?? :(
ArrayList<Integer> list = new ArrayList<Integer>();
// the above line is in a different method in the same class, but it's relevant here
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null)
{
// I want the following line to read "218 150 500 330", and to store each individual integer into the list. I don't know why it won't work :(
list.add(Integer.parseInt(src.next().trim()));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//print out the list
System.out.println(list);
Thank you for the help! I'm sure that I'm just missing something really simple...
You can use a Scanner(String) like
while ((text = reader.readLine()) != null) {
Scanner scanner = new Scanner(text);
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
}
Of course, your entire method could be simplified by using a try-with-resources Statement and the diamond operator and just Scanner(File) like
public static void main(String[] args) {
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
List<Integer> list = new ArrayList<>();
try (Scanner scanner = new Scanner(file);) {
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
} catch (Exception e) {
e.printStackTrace();
}
// print out the list
System.out.println(list);
}
Do this inside the while loop
String[] individualArray = text.split(" ");//note space
for(String individual:individualArray){
yourList.add(individual);//You need to parse it to integer here as you have already done
}
In the above code, individualArray will contain each individual integers that are separated by space. And inside the for loop each string needs to be parsed to integer and then added to your list
try this :
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null)
{
// you need only this for loop in you code.
for (String value : text.split(" ")) { // get list of integer
if(!value.equals("")) // ignore space
list.add(Integer.parseInt(value)); // add to list
}
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
// print out the list
System.out.println(list);
}

Using useDelimiter() in Java to isolate a piece of text

I have a text file with content that looks like this:
Event=ThermostatNight,time=0
Event=LightOn,time=2000
Event=WaterOff,time=8000
Event=ThermostatDay,time=10000
Event=Bell,time=9000,rings=5
Event=WaterOn,time=6000
Event=LightOff,time=4000
Event=Terminate,time=12000
I have to use a Scanner to grab the file and then loop through each of the lines of text and isolate each event. For example I need to isolate "ThermostatNight" in the first line and then put it in an array, the next one would be "LightOn", and so on. It's a small piece of a large project that I am working on for an intermediate Java course. I have been able to get exactly the opposite of what I want with the useDelimiter argument shown below. Is there a quick fix to this. Note that I must use the useDelimiter() method.
public void readFile2() {
array2 = new ArrayList<String>();
while (s.hasNext()) {
s.useDelimiter("=(.*?),");
array2.add(s.next());
}
You can use multiples delimiter.
//scanner.useDelimiter("Event=|,time=([0-9]*)");
scanner.useDelimiter("Event=|,(.)+[\\r\\n]*Event=|,(.)+[\\r\\n]*");
//for better you can use this
//scanner.useDelimiter("Event=|,time=([0-9]**)[\\r\\n]**Event=|,time=([0-9]*)");
while (scanner.hasNext())
{
System.out.println(scanner.next());
}
Probably not the best , but it will work
Since you have requirement to use only useDelimeter and if the structure not changed.
then
public static void main(String[] args) {
Scanner sc;
try {
sc = new Scanner(new File("/home/xxx/text.txt"));
sc.useDelimiter(",time=(.*?)\\nEvent=");
ArrayList<String> eventlist = new ArrayList<String>();
String tmp = null;
if (sc.hasNext()) {
tmp = sc.next();
tmp = tmp.split("=")[1]; // Just First line
}
while (sc.hasNext()) {
eventlist.add(tmp);
System.out.println(tmp); // for test only remove it
tmp = sc.next();
}
tmp = tmp.split(",")[0];
eventlist.add(tmp);
System.out.println(tmp); // for test only , remove it
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories