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

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

Related

How can I sort a Ranking list using a specific column from a file and print the whole file sorted?Java

Already done this but can't make it work.
Also tried to create another while ((line = br.readLine()) != null) {}, and placed the sort before it, but it won't read this while so it wouldnt print anithing.
The file looks like this:
1-Fred-18-5-0
2-luis-12-33-0
3-Helder-23-10-0
And wanted it to print like this:
2-luis-12-33-0
3-Helder-23-10-0
1-Fred-18-5-0
public static void lerRanking() throws IOException {
File ficheiro = new File("jogadores.txt");
BufferedReader br = new BufferedReader(new FileReader(ficheiro));
List<Integer> jGanhos = new ArrayList<Integer>();
int i = 0;
String line;
String texto = "";
while ((line = br.readLine()) != null) {
String[] col = line.split("-");
int colunas = Integer.parseInt(col[3]);
jGanhos.add(colunas);
i++;
if(i>=jGanhos.size()){
Collections.sort(jGanhos);
Collections.reverse(jGanhos);
for (int j = 0; j < jGanhos.size(); j++) {
if(colunas == jGanhos.get(i)){
texto = texto + line + "\n";
}
}
}
}
PL(texto);
}
Make it step by step:
public static void lerRanking() throws IOException {
File ficheiro = new File("jodagores.txt");
// read file
BufferedReader br = new BufferedReader(new FileReader(ficheiro));
List<String> lines = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
// sort lines
lines.sort(new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// sort by 3rd column descending
return Integer.parseInt(s2.split("-")[3]) - Integer.parseInt(s1.split("-")[3]);
}
});
// concat lines
String texto = "";
for (String l : lines) {
texto += l + "\n";
}
System.out.println(texto);
// PL(texto);
}
Okay so first of all I thounk you should introduce a Java class (in my code this is ParsedObject) to manage your objects.
Second it should implement the Comparable<ParsedObject> interface, so you can easily sort it from anywhere in the code (without passing a custom comparator each time).
Here is the full code:
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
lerRanking();
}
public static void lerRanking() throws IOException {
File ficheiro = new File("jodagores.txt");
// read lines to a list
List<String> lines = readLines(ficheiro);
// parse them to a list of objects
List<ParsedObject> objects = ParsedObject.from(lines);
// sort
Collections.sort(objects);
// print the output
writeLines(objects);
}
public static List<String> readLines(File ficheiro) throws IOException {
// read file line by line
BufferedReader br = new BufferedReader(new FileReader(ficheiro));
List<String> lines = new ArrayList<>();
String line;
while((line = br.readLine()) != null) {
lines.add(line);
}
br.close(); // THIS IS IMPORTANT never forget to close a Reader :)
return lines;
}
private static void writeLines(List<ParsedObject> objects) throws IOException {
File file = new File("output.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for(ParsedObject object : objects) {
// print the output line by line
bw.write(object.originalLine);
}
bw.flush();
bw.close(); // THIS IS IMPORTANT never forget to close a Writer :)
}
// our object that holds the information
static class ParsedObject implements Comparable<ParsedObject> {
// the original line, if needed
public String originalLine;
// the columns
public Integer firstNumber;
public String firstString;
public Integer secondNumber;
public Integer thirdNumber;
public Integer fourthNumber;
// parse line by line
public static List<ParsedObject> from(List<String> lines) {
List<ParsedObject> objects = new ArrayList<>();
for(String line : lines) {
objects.add(ParsedObject.from(line));
}
return objects;
}
// parse one line
public static ParsedObject from(String line) {
String[] splitLine = line.split("-");
ParsedObject parsedObject = new ParsedObject();
parsedObject.originalLine = line + "\n";
parsedObject.firstNumber = Integer.valueOf(splitLine[0]);
parsedObject.firstString = splitLine[1];
parsedObject.secondNumber = Integer.valueOf(splitLine[2]);
parsedObject.thirdNumber = Integer.valueOf(splitLine[3]);
parsedObject.fourthNumber = Integer.valueOf(splitLine[4]);
return parsedObject;
}
#Override
public int compareTo(ParsedObject other) {
return other.thirdNumber.compareTo(this.thirdNumber);
}
}
}
If you have any more question feel free to ask :) An here is an the example objects list after parsing and sorting.
The easiest way is to first create a class that will hold the data from your file provided your lines keep the same format
public class MyClass {
private Integer column1;
private String column2;
private Integer column3;
private Integer column4;
private Integer column5;
public MyClass(String data) {
String[] cols = data.split("-");
if (cols.length != 5) return;
column1 = Integer.parseInt(cols[0]);
column2 = cols[1];
column3 = Integer.parseInt(cols[2]);
column4 = Integer.parseInt(cols[3]);
column5 = Integer.parseInt(cols[4]);
}
public synchronized final Integer getColumn1() {
return column1;
}
public synchronized final String getColumn2() {
return column2;
}
public synchronized final Integer getColumn3() {
return column3;
}
public synchronized final Integer getColumn4() {
return column4;
}
public synchronized final Integer getColumn5() {
return column5;
}
#Override
public String toString() {
return String.format("%d-%s-%d-%d-%d", column1, column2, column3, column4, column5);
}
}
Next you can get a list of your items like this:
public static List<MyClass> getLerRanking() throws IOException {
List<MyClass> items = Files.readAllLines(Paths.get("jogadores.txt"))
.stream()
.filter(line -> !line.trim().isEmpty())
.map(data -> new MyClass(data.trim()))
.filter(data -> data.getColumn4() != null)
.sorted((o1, o2) -> o2.getColumn4().compareTo(o1.getColumn4()))
.collect(Collectors.toList());
return items;
}
This will read your whole file, filter out any blank lines, then parse the data and convert it to MyClass.
It will then make sure that column4 isn't null in the converted objects.
Finally it will reverse sort the objects based off from the value in column 4 and create a list of those items.
To print the results you can do something like this
public static void main(String[] args) {
List<MyClass> rankingList = getLerRanking();
rankingList.forEach(item -> System.out.println(item));
}
Since we overrode the toString() method, it will print it out the object as it is displayed in the file.
Hope this helps.

creating multiple arraylists from a file in 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;
}
}

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 do I pas instances, created in a class method, to another method in the same class?

I've created this Class:
class File {
public String path;
public int numberOfLines = 0;
public String[] fileContent;
public File (String file_path) {
path = file_path;
}
public BufferedReader openFile () throws IOException {
FileReader ReadFile = new FileReader(path);
BufferedReader ReadFilePerLine = new BufferedReader(ReadFile);
}
public int countLines () {
String line;
while((line = ReadFilePerLine.readLine()) != null){
numberOfLines++;
}
return numberOfLines;
}
public String[] readLines () {
String[] fileContent = new String[numberOfLines];
for (int i=0; i < numberOfLines; i++){
fileContent[i] = ReadFilePerLine.readLine();
}
}
}
How do I get the countLines() method to know of the existence of ReadFilePerLine and how do I get him to use it? (same for the numberOfLines variable)
BufferedReader ReadFilePerLine = new BufferedReader(ReadFile);
this is a local variable of the openFile() method, and therefore exists only within the scope of that method.
If you want it to be accessible to other methods, make it an instance variable (i.e. move BufferedReader ReadFilePerLine; to be outside the method).
You should use method arguments for that, like this:
public int countLines (BufferedReader in) {
String line;
while((line = in.readLine()) != null){
numberOfLines++;
}
return numberOfLines;
}

How can I read the data from file into the index for a 2d array?

my data looks like:
1 2 3
1 3 7
2 1 6
4 3 8
I hope to get an array c[i][j] that the first col of the data is [i], the second col is [j], and the value goes into the array.
And I am new to java, I read sth about file input, like:
import java.io.*;
public class Words {
public static void main(String[] args)
throws FileNotFoundException, IOException {
processFile("words.txt");
}
public static void processFile(String filename)
throws FileNotFoundException, IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader in = new BufferedReader(fileReader);
while (true) {
String s = in.readLine();
if (s == null) break;
System.out.println(s);
}
}
}
Is their a good way to change the code into what I want?
Thank you for your help!
This should do the trick. Its basically the same, but I added also parsing methods. You can parse each line using "split" and then you can easily convert it to integer by valueOf method.
public static void main(String[] args)
throws FileNotFoundException, IOException {
processFile("words.txt");
}
public static void processFile(String filename) throws FileNotFoundException, IOException {
int[][] array = new int[4][3];
int lineCount = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line = br.readLine();
while (line != null) {
String[] parts = line.split(" ");
for (int i = 0; i < parts.length; i++) {
array[lineCount][i] = Integer.valueOf(parts[i]);
}
lineCount++;
line = br.readLine();
}
}
}
If the input is guaranteed to be 3 numbers (integers, not floating point), separated by 2 spaces, then you can use this.
If the input will be variable or untrustworthy then you can add more checks before parsing.
private static ArrayList<Integer[]> list;
public static void main(String[] args) throws FileNotFoundException, IOException
{
processFile("words.txt");
}
public static void processFile(String filename) throws FileNotFoundException, IOException, NumberFormatException
{
BufferedReader in = new BufferedReader(new FileReader(filename));
String line = null;
list = new ArrayList<Integer[]>();
while((line = in.readLine()) != null)
{
String[] split = line.split("\\s{1}");
list.add(
new Integer[]
{
Integer.parseInt(split[0]),
Integer.parseInt(split[1]),
Integer.parseInt(split[2]),
});
}
}
Although, you should technically be doing it like this:
private static ArrayList<Integer[]> list;
public static void main(String[] args) throws FileNotFoundException, IOException
{
processFile("words.txt");
}
public static void processFile(String filename) throws FileNotFoundException, IOException, NumberFormatException
{
BufferedReader in = null;
String line = null;
list = new ArrayList<Integer[]>();
try
{
in = new BufferedReader(new FileReader(filename));
while((line = in.readLine()) != null)
{
String[] split = line.split("\\s{1}");
list.add(
new Integer[]
{
Integer.parseInt(split[0]),
Integer.parseInt(split[1]),
Integer.parseInt(split[2]),
});
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
throw e;
}
catch(IOException e)
{
e.printStackTrace();
throw e;
}
catch(NumberFormatException e)
{
e.printStackTrace();
throw e;
}
catch(Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
if(in != null)
{
in.close();
}
}
}

Categories

Resources