Trying to separate a txt file into two ArrayLists? - java

This image is a text file I need to separate by date and the digits alongside it
BufferedReader wordReader = new BufferedReader(new FileReader("\\Users\\rosha\\eclipse-workspace\\working\\src\\workingfix\\spx_data_five_years.txt"));
ArrayList<String> spxIndex = new ArrayList<>();
ArrayList<String> date = new ArrayList<>();
//populating the Array with the file
String line = wordReader.readLine();
while (line != null) {
date.add(line);
line = wordReader.readLine();
}
wordReader.close();
Would really love to understand how to separate this file into two Arrays. Been at it for a while and some Guidance in the right direction would be incredible. Apologies if it's a simple solution for some reason I'm having trouble getting started.
Here is the some of the Text File, if I can get guidance on this I'll be in good shape
1/4/2010 1132.99
1/5/2010 1136.52
1/6/2010 1137.14
1/7/2010 1141.69
1/8/2010 1144.98
1/11/2010 1146.98
1/12/2010 1136.22
1/13/2010 1145.68

Your two examples are a little bit different, in the Image, it seems like the entries are separated by a tab. In your text example, the entries are separated by a space. If they are separated by a space, a simple String[] splitter = line.split(" "); suffices. This gives you the result as an Array, which you can write in the ArrayLists.

Here is the solution, using split method
public static void main(String[] args) throws IOException {
ArrayList<String> spxIndex = new ArrayList<>();
ArrayList<String> date = new ArrayList<>();
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader("\\Users\\rosha\\eclipse-workspace\\working\\src\\workingfix\\spx_data_five_years.txt"));
while ((sCurrentLine = br.readLine()) != null) {
String[] lineValues = sCurrentLine.split(" ");
date.add(lineValues[0]);
spxIndex.add(lineValues[1]);
}
br.close();
System.out.println(date);
System.out.println(spxIndex);
}

Related

How to split an ArrayList of sentences into an ArrayList of words in Java without reading a text file more than once?

I need to read a text file only once and store the sentences into an ArrayList. Then, I need to split the ArrayList of sentences into another ArrayList of each individual word. Not sure how to go about doing this?
In my code, I've split all the words into an ArrayList, but I think it's reading from the file again, which I can't do.
My code so far:
public class Main {
public static void main(String[] args){
try{
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
ArrayList<String> sentences = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
String line;
while((line=br.readLine()) != null){
String[] lines = line.toLowerCase().split("\\n|[.?!]\\s*");
for (String split_sentences : lines){
sentences.add(split_sentences);
}
/*Not sure if the code below reads the file again. If it
does, then it is useless.*/
String[] each_word = line.toLowerCase().split("\\n|[.?!]\\s*|\\s");
for(String split_words : each_word){
words.add(split_words);
}
}
fr.close();
br.close();
String[] sentenceArray = sentences.toArray(new String[sentences.size()]);
String[] wordArray = words.toArray(new String[words.size()]);
}
catch(IOException e) {
e.printStackTrace();
}
}
}
/*Not sure if the code below reads the file again. If it does, then it is useless.*/
It doesn't. You are simply reparsing the line that you have already read.
You have already solved your problem.

Retrieving variables from a text file through a hashmap

I am creating a school program for a project in which I a writing words and translations to a file, (separated by a character). I have read that I can read them via a hash map into an array. I was just wondering if someone could point me in the right direction as how to do this.
If anyone has a better idea of how to store and retrieve the words I would love to learn. The reason I am writing to a file is so the user can store as many words as they want.
Thank-you so much :D
You can use java.util.HashMap to store user words and related translations:
String userWord = null;
String translation = null, translation1 = null;
Map<String, String[]> map = new HashMap();
map.put(userWord, new String[] { translation, translation1 });
String[] translations = map.get(userWord);
This map lets you map single userWord to multiple translations.
Here's a reference for learning how to use BufferedReader: BufferedReader
Here's a reference for learning how to use FileReader: FileReader
import java.io.*;
class YourClass
{
public static void main() throws IOException
{
File f = new File("FilePath"); // Replace every '\' with '/' in the file path
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = "";
String FileString = "";
while((line = br.readLine()) != null)
{
// Now 'line' contains each line of the file
// If you want, you can store the entire file in a String, like this:
FileString += line + "\n"; // '\n' to register each new line
}
System.out.println(FileString);
}
} // End of class
I'm still a newbie, and don't understand much about HashMap, but I can tell you how to store it in a String array:
FileString = FileString.replaceAll("\\s+", " ");
String[] Words = FileString.split(" ");
FileString.replaceAll("\\s+", " ") - Replaces 1 or more spaces with 1 space, so as to avoid any logical errors.
FileString.split(" ") - Returns a String array of each String separated by a space.
You can try something like this
File f = new File("/Desktop/Codes/Text.txt");
// enter your file location
HashMap<String, String[]> hs = new HashMap<String, String[]>();
// throw exception in main method
Scanner sc = new Scanner(f);
String s="";
while(sc.hasNext()){
s = sc.next();
// create a method to search translation
String []trans = searchTrans(s);
hs.put(s, trans);
}

How to mask the content of a text file in Java

I am looking to mask the content of a text file.
Ex: The text file contains data like
Peter|peter#gmail.com|312-445-9988|....|
John|john#gmail.com|123-457-6789|....|
Expected Output:
Peter|XXXXX#gmail.com|XXX-XXX-XXXX|....|
John|XXXX#gmail.com|XXX-XXX-XXXX|....|
I have to mask the content like phone number and mail ID till peter not #gmail.com
Here is my code that I tried I have tried till reading the data from the text file after that I am not getting any ideas...
public class DataMasking {
public static void main(String args[]) throws IOException{
BufferedReader in = new BufferedReader(new FileReader("Filepath"));
String str;
List<String> parts = new ArrayList<String>();
while ((str = in.readLine()) != null) {
parts.add(str);
}
int size = parts.size();
//we are reducing the size by one because we are not counting the first line(Only contains file name and time stamp).
size = size-1;
System.out.println("The Number of lines in the text file "+size);
Any help is appreciated.
Okay so may be you want something like this. Try it -
BufferedReader in = new BufferedReader(new FileReader("filepath"));
String str;
List<String> parts = new ArrayList<String>();
while ((str = in.readLine()) != null) {
parts.add(str);
}
List<String> newList = new ArrayList<String>();
List<String> emailPart=new LinkedList<String>();
List<String> numberPart=new LinkedList<String>();
for(int i=1;i<parts.size();i++){
String[] strArr=parts.get(i).split("\\|");
for(int j=0;j<strArr.length;j++){
if(strArr[j].matches(".*#.*")){
int index=strArr[j].indexOf("#");
emailPart.add(strArr[j].substring(0, index).replaceAll("[A-Za-z0-9]", "X")+
strArr[j].substring(index, strArr[j].length()));
}
if(strArr[j].matches("[0-9\\-]+")){
numberPart.add(strArr[j].replaceAll("[0-9]", "X"));
}
}
newList.add(strArr[0]+"|"+emailPart.get(i-1)+"|"+numberPart.get(i-1));
}
System.out.println(newList);

How to read a txt file to an ArrayList of unknown size

How do I read from a txt file with lines of unknown size? For example:
Family1,john,mark,ken,liam
Family2,jo,niamh,liam,adam,apple,joe
Each line has a different number of names. I am able to read in when using object type like
family(parts[0], parts[1], parts[2])
but thats if I know the amout that will be in each. how do I read it in without knowing how many will be in each?
FileReader fr = new FileReader("fam.txt");
BufferedReader br = new BufferedReader(fr);
String fileLines;
String[] parts;
while(br.ready())
{
fileLines = br.readLine();
parts = fileLines.split(",");
.
.
You can use varargs for your family() method to accept the array: family(String ... parts) or just use family(String[] parts).
Personally, I would create a separate class Family and not pollute it with implementation detail about the file format (i.e. that the first item on each line is the family name):
public class Family {
private final List<String> members = new ArrayList<>();
private final String familyName;
public Family(String familyName, Collection<String> members) {
this.familyName = familyName;
this.members.addAll(members);
}
}
Then your loop can be like this:
List<Family> families = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
List<String> parts = Arrays.asList(line.split(","));
String familyName = parts.remove(0);
families.add(new Family(familyName, parts));
}
ArrayList<E>: Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null, provides methods to manipulate the size of the array that is used internally to store the list.
Each ArrayList instance has a capacity: size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
So just read your data and add to the array-list using ArrrayList.add(E e) method.
You're struggling since you try to load the data to an String[] which is in turn a plain array. You should use ArrayList that maintains an internal array and it increase its size dynamically.
FileReader fr = new FileReader("fam.txt");
BufferedReader br = new BufferedReader(fr);
String fileLines;
String[] parts;
List<List<String>> data = new ArrayList<>();
while(br.ready()) {
fileLines = br.readLine();
parts = fileLines.split(",");
data.add(Arrays.asList(parts));
//do what you want/need...
}
//do what you want/need...
A better approach would be parsing the data in String[] parts and build an object of some class that will contain the data for your specific case:
public void yourMethod() {
FileReader fr = new FileReader("fam.txt");
BufferedReader br = new BufferedReader(fr);
String fileLines;
String[] parts;
List<Family> familyList = new ArrayList<>();
while(br.ready()) {
fileLines = br.readLine();
parts = fileLines.split(",");
Family family = new Family(parts[0], parts[1], parts[2]);
familyList.add(family);
//do what you want/need...
}
//do what you want/need...
}
My personal preference is to use the Scanner class. You can review the functionality here. With the scanner you can parse the file a line at a time and store those values into a String.
Scanner scan = new Scanner(new File("fam.txt"));
List<String> families = new ArrayList<String>();
while(scan.hasNextLine()){
families.add(scan.nextLine());
}
Then you can do whatever you want with the families in the ArrayList
use a Scanner, that's much easier. You can put both in a while loop
Scanner sc = new Scanner(new File(myFile.txt));
while(sc.hasNextLine()) {
while(sc.hasNextString()) {
String str = sc.nextString();
}
}
This is a simplefied version and it will not work correctly, because you have to store some values in variables for Java to read them correctly. Read the documentation on the Java Scanner to find a more detailed explanation. The Scanner is much easier than what you have been doing

ArrayList to Array

How do I convert this ArrayList's value into an array? So it can look like,
String[] textfile = ... ;
The values are Strings (words in the text file), and there are more than a 1000 words. In this case I cannot do the, words.add("") 1000 times. How can I then put this list into an array?
public static void main(String[]args) throws IOException
{
Scanner scan = new Scanner(System.in);
String stringSearch = scan.nextLine();
List<String> words = new ArrayList<String>(); //convert to array
BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
You can use
String[] textfile = words.toArray(new String[words.size()]);
Relevant Documentation
List#toArray(T[])
words.toArray() should work fine.
List<String> words = new ArrayList<String>();
String[] wordsArray = (String[]) words.toArray();
you can use the toArray method of Collection such as shown here
Collection toArray example
List<String> words = new ArrayList<String>();
words.add("w1");
words.add("w2");
String[] textfile = new String[words.size()];
textfile = words.toArray(textfile);

Categories