creating multiple arraylists from a file in java - java

i am new to java so i need help...
i have a file which contains:-
Model
A
T
ENMDL
Model
A
T
ENMDL
.... repeat multiple times and i need to make a program which separate them and store them in different arraylists.
can anyone help..
public ArrayList<String> GetAllFile(String File) throws IOException
{
FileReader fr=new FileReader(File);
BufferedReader br=new BufferedReader(fr);
String rowData;
ArrayList<String> allFile = new ArrayList<String>();
while((rowData=br.readLine())!=null)
if(rowData.startsWith("MODEL"))
allFile.add(rowData);
fr.close();
return allFile;
}
}

Change your return type.
public static List<List<String>> fileToArrayList(String fileName) {
Create the outer container.
List<List<String>> allFile = new ArrayList<>();
Then outside of your loop.
List<String> modelLines = new ArrayList<>();
Then the condition inside of your loop should be.
if(rowData.startsWith("Model")){
modelLines = new ArrayList<>();
allFile.add(modelLines);
} else{
modelLines.add(rowData);
}

Here is an solution that might suit you:
public class FileToArrayList {
public static void main(String[] args) {
// Get the file as an List.
List<String> fileAsList = FileToArrayList.fileToArrayList("SomeFile.txt");
// Print the lines.
for (String oneLine : fileAsList) {
System.out.println(oneLine);
}
}
public static List<String> fileToArrayList(String fileName) {
// Container for the lines.
List<String> lines = new ArrayList<>();
// Try with resources, it will close it automatically afterwards.
try(FileReader fr = new FileReader(new File(fileName))) {
BufferedReader br = new BufferedReader(fr);
String line;
// line = br.readLine() is an expression which will return line, therefore
// we can check if that expression is not null, because
// when its null, we reached EOF (end of file)
while((line = br.readLine()) != null) {
lines.add(line);
}
} catch(IOException e) {
e.printStackTrace();
}
return lines;
}
}

Related

I want to split textfile into mutilple text files

Hi I have Text file having some tag based data and i want to split into multiple text files.
Main Text files having data like this:
==========110CYL067.txt============
<Entity Text>Cornell<Entity Type>Person
<Entity Text>Donna<Entity Type>Person
<Entity Text>Sherry<Entity Type>Person
<Entity Text>Goodwill<Entity Type>Organization
==========110CYL068.txt============
<Entity Text>Goodwill Industries Foundation<Entity Type>Organization
<Entity Text>Goodwill<Entity Type>Organization
NOTE: Over here 110CYL068.txt and 110CYL067.txt are text files.
I want to split this file into 110CYL068.txt and 110CYL067.txt and so on.
This ============ pattern is fixed.Between ============ FileName ============
file name could be anything.does anyone have any insight.
I don't want to write codes for you, so you can read the file using a BufferedReader or FileReader. You can create and write to a new File using any file writer whenever you see a line starting with ======= or containing .txt.
If you encounter those close the previous file and repeat the process.
Done ppl way to complicatet just did it fast and dirty.
public static List<String> lines = new ArrayList<String>();
public static String pattern = "==========";
public static void main(String[] args) throws IOException {
addLines(importFile());
}
private static List<String> importFile() throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\temp\\test.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
lines.add(line.replaceFirst(pattern, ";") + "\n");
line = br.readLine();
}
} finally {
br.close();
}
return lines;
}
private static void addLines(List<String> list) throws IOException {
String FilesString = list.toString();
System.out.println(FilesString);
String[] FilesArray = FilesString.split(";");
for (String string : FilesArray) {
createFile(string);
}
}
private static void createFile(String content) throws IOException {
String[] Lines = content.replaceAll("=", "").split("\n");
File file = new File("C:\\temp\\" + Lines[0]);
file.createNewFile();
FileWriter writer = new FileWriter(file);
Lines[0] = null;
for (String Line : Lines) {
if (Line != null) {
writer.append(Line.replace(",", "")+"\n");
}
}
writer.flush();
writer.close();
}
}
Also quick and dirty, not using regex. I don't really recommend doing it like this because the for loop in main is quite confusing and could break, but it might be beneficial to use this for ideas.
import java.io.*;
import java.util.*;
class splitFiles {
public static void main(String[] args){
try {
List<String> fileRead = readFiles("some.txt");
for(int i=0; i<fileRead.size(); i++){
if(fileRead.get(i).charAt(0) == '='){
PrintWriter writer = new PrintWriter(getFileName(fileRead.get(i)), "UTF-8");
for(int j=i+1; j<fileRead.size(); j++){
if(fileRead.get(j).charAt(0) == '='){
break;
} else {
writer.println(fileRead.get(j));
}
}
writer.close();
}
}
} catch (Exception e){
}
}
public static String getFileName(String fileLine){
String[] split = fileLine.split("=");
for(String e: split){
if(e.isEmpty()){
continue;
} else {
return e;
}
}
return "No file name found";
}
public static ArrayList<String> readFile(String path){
try {
Scanner s = new Scanner(new File(path));
ArrayList<String> list = new ArrayList<String>();
while(s.hasNext()){
list.add(s.next());
}
s.close();
return list;
} catch (FileNotFoundException f){
System.out.println("File not found.");
}
return null;
}
static List<String> readFiles(String fileName) throws IOException {
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();
return words;
}
}

How to store the data from other class to an array?

public class CompetitorFileReader {
public String line;
public static ArrayList<String> list = new ArrayList<String>();
public void Mary() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("competitors.txt"));
while ((line = br.readLine()) != null)
{
list.add(line);
}
public String Mary() throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("competitors.txt")) ;
while ((line = br.readLine()) != null)
{
list.add(line);
}
String[] lineobjects = list.get(0).split(",");
System.out.println("Competitor:"+lineobjects[0]);
System.out.println("Competitor ID:"+lineobjects[1]);
System.out.println("Competitor Event:"+lineobjects[2]);
System.out.println("Performance:"+lineobjects[3]);
return line;
}
//
public static void main(String[] args) {
String[] data = {CompetitorFileReader.Mary()};
}
}
Can i do like this? i am just not know how to put the first class of Mary to the array of the main class.i change it now, is it correct?
yes you can,
just create a new instance of your class (CompetitorFileReader), call your method (Mary), then add your list data into your array (you should loop through them and add them one by one).
public static void main(String[] args)
{
CompetitorFileReader competitor = new CompetitorFileReader();
competitor.Mary();
String [] data = new String[CompetitorFileReader.list];
int i=0;
for(String s : CompetitorFileReader.list){
data[i++] = s;
}
}

ArrayList different method's scope

I have a problem with the code below. I'm getting different results base on where the line list = new ArrayList<InClass>(); is declared. In place //B but everything works fine when I add it to //A and I cannot understand the difference. Here is the code:
import java.util.*;
import java.io.*;
public class ArrayListOne {
private ArrayList<InClass> list;
private InClass in;
public static void main(String args[]) {
ArrayListOne a = new ArrayListOne();
a.readFile();
}
public void readFile() {
//A
/**
* adding "list = new ArrayList<InClass>();"
* getting all 4 lines of test.txt
*/
try {
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
assignToObject(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
readObject();
}
public void assignToObject(String s) {
//B
/**
* adding "list = new ArrayList<InClass>();"
* getting just last line of test.txt
*/
InClass n = new InClass(s);
list.add(n);
System.out.println(list.size());
}
public void readObject() {
for (int i=0; i<list.size(); i++) {
in = list.get(i);
System.out.println(in.stTest);
}
}
//inner class
public class InClass {
String stTest;
public InClass(String s) {
stTest = s;
}
}
}
the test.txt has 3 lines. in //A, I'm getting all three lines (what I want) but in //B I just get the last line.
It's easier to see the difference if you "inline" assignToObject() by copy-pasting the contents of assignToObject() to the proper place in readFile():
public void readFile() {
// B
// list = new ArrayList<InClass>();
try {
File file = new File("test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
// Here is where assignToObject() was //
// B
// list = new ArrayList<InClass>();
InClass n = new InClass(line);
list.add(n);
System.out.println(list.size());
}
} catch (Exception ex) {
ex.printStackTrace();
}
readObject();
}
Now think about if you put list = new ArrayList<InClass>() in A and B.
If you declare list = new ArrayList<InClass>() at A (i.e. inside readFile()), the statement will be executed once -- when readFile() is called in main(). So you'll end up with one ArrayList containing everything you need.
However, if you declare list = new ArrayList<InClass>() at B (i.e. inside assignToObject()), you'll get a new list for every line you read (i.e. every time you call assignToObject()). This means that every iteration you'll end up with a new ArrayList that only contains the most recently read line. The ArrayList containing the previous line was thrown away, as the reference that used to point to it now points to a new object.

Reading file to ArrayList

I'm trying to write a .dat file to an ArrayList. The file contains lines formatted like this : #name#,#number#.
Scanner s = new Scanner(new File("file.dat"));
while(s.hasNext()){
String string = s.next();
names.add(string.split(",")[0];
numbers.add(Integer.parseInt(string.split(",")[1];
}
If I check if it runs with printing, all I get is the first line.
With standard Java libraries (full code example):
BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("myfile.txt"));
String str;
while ((str = in.readLine()) != null) {
myList.add(str);
//Or split your read string here as you wish.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
With other common libraries:
A one-liner with commons-io:
List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");
The same with guava:
List<String> lines =
Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));
Then you can iterate over the read lines and split each String to your desired ArrayLists.
Instead of using a Scanner, use a BufferedReader. The BufferedReader provides a method to read one line at a time. Using this, you can process every line individually by splitting them (line.split(",")) , stripping the trailing hashes, then pushing them into your ArrayLists.
This is how I read a file and turn it into a arraylist
public List<String> readFile(File file){
try{
List<String> out = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
while((line = reader.readLine()) != null){
if(line != null){
out.add(line);
}
}
reader.close();
return out;
}
catch(IOException e){
}
return null;
}
Hope it helps.
May be this is lengthy way but works:
text file:
susheel,1134234
testing,1342134
testing2,123455
Main class:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Equal {
public static void main(String[] args) {
List<Pojo> data= new ArrayList<Pojo>();
String currentLine;
try {
BufferedReader br = new BufferedReader(new FileReader("E:\\test.dat"));
while ((currentLine = br.readLine()) != null) {
String[] arr = currentLine.split(",");
Pojo pojo = new Pojo();
pojo.setName(arr[0]);
pojo.setNumber(Long.parseLong(arr[1]));
data.add(pojo);
}
for(Pojo i : data){
System.out.print(i.getName()+" "+i.getNumber()+"\n");
}
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
}
POJO class:
public class Pojo {
String name;
long number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
}

Sorting a text file in Java

I have a text file with a list of words which I need to sort in alphabetical order using Java. The words are located on seperate lines.
How would I go about this, Read them into an array list and then sort that??
This is a simple four step process, with three of the four steps addressed by Stackoverflow Questions:
Read each line and turn them into Java String
Store each Java String in a Array (don't think you need a reference for this one.)
Sort your Array
Write out each Java String in your array
Here is an example using Collections sort:
public static void sortFile() throws IOException
{
FileReader fileReader = new FileReader("C:\\words.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
Collections.sort(lines, Collator.getInstance());
FileWriter writer = new FileWriter("C:\\wordsnew.txt");
for(String str: lines) {
writer.write(str + "\r\n");
}
writer.close();
}
You can also use your own collation like this:
Locale lithuanian = new Locale("lt_LT");
Collator lithuanianCollator = Collator.getInstance(lithuanian);
import java.io.*;
import java.util.*;
public class example
{
TreeSet<String> tree=new TreeSet<String>();
public static void main(String args[])
{
new example().go();
}
public void go()
{
getlist();
System.out.println(tree);
}
void getlist()
{
try
{
File myfile= new File("C:/Users/Rajat/Desktop/me.txt");
BufferedReader reader=new BufferedReader(new FileReader(myfile));
String line=null;
while((line=reader.readLine())!=null){
addnames(line);
}
reader.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
void addnames(String a)
{
tree.add(a);
for(int i=1;i<=a.length();i++)
{
}
}
}
public List<String> readFile(String filePath) throws FileNotFoundException {
List<String> txtLines = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while (!((line = reader.readLine()) == null)) {
txtLines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return txtLines.stream().sorted().collect(Collectors.toList());
}

Categories

Resources