I have a method that should return a 2D-array which is always structured like this:
int [][] = {{100}, {5}, {1,5,7,8,30,60,...}
My problem is that when I call the method I don't know how long the 3rd array will be. This is my code right now:
public static int[][] readFile(int max, int types, String fileName) {
int [][]result = new int[3][];
try {
FileReader reader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println(line);
if (currentLine == 0) {
result[0][0] = Integer.parseInt(numbers[0]);
result[1][0] = Integer.parseInt(numbers[1]);
}else if (currentLine == 1) {
int []theSlices = new int[numbers.length];
result[2][0] = theSlices; //-> obviously error
for(int i = 0; i<numbers.length; i++) {
theSlices[i] = Integer.parseInt(numbers[i]);
}
return result;
}
currentLine++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
;
return null;
}
My code right now is obviously not working but how can I fix it? Happy for every help :)
Related
Have a two text file with words list. need save both file in two array.I know how to do it using list and set.. but here I want know how to do it using only arrays.Only array and no predefined functions such as Arrays.sort() or Collections.sort() can be used
no list no ArrayList or no class from Java Collection Frameworks can be used.
public class Main {
public static Set<String> setlist1= new HashSet<>();
public static String[] arrayList=new String[file1count];
public static String[] array2=new String[file2count];
public static int file1count=0;
public static int file2count=0;
public static void main(String[] args) {
try {
/*read the files*/
Scanner rf= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt")));
Scanner rf2= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt")));
String line;
String line2;
while(rf.hasNext()){
line=rf.nextLine();
file1count++;
}
while(rf2.hasNext()){
line2=rf2.nextLine();
file2count++;
}
rf.close();
rf2.close();
}catch(IOException e){
System.out.println(e);
}
}
}
The problem with using arrays is that you don't know in advance what length to allocate.
You basically have two options:
read each file twice
allocate an array of some initial length, and reallocate is as needed (that's what an ArrayList does.)
Second option: let's have a method readFile that reads all the lines from a file and returns an array:
public static String[] readFile(String fileName) throws IOException {
try (Reader reader = new FileReader(fileName);
BufferedReader in = new BufferedReader(reader)) {
String[] lines = new String[10]; // start with 10
int count = 0;
String line;
while ((line = in.readLine()) != null) {
if (count >= lines.length) {
lines = reallocate(lines, count, 2*lines.length);
}
lines[count++] = line;
}
if (count < lines.length) {
// reallocate to the final length;
lines = reallocate(lines, count, count);
}
return lines;
}
}
private static String[] reallocate(String[] lines, int count,
int newLength) {
String[] newArray = new String[newLength];
for (int i = 0; i < count; ++i) {
newArray[i] = lines[i];
}
lines = newArray;
return lines;
}
BufferedReader reader1 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt"));
BufferedReader reader2 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt"));
String line1 = reader1.readLine();
String[] array1 = new String[10000000];
String[] array2 = new String[10000000];
String line2 = reader2.readLine();
boolean areEqual = true;
int lineNum = 1;
while (line1 != null || line2 != null) {
if (line1 == null || line2 == null) {
areEqual = false;
break;
} else if (!line1.equalsIgnoreCase(line2)) {
areEqual = false;
break;
}
if (line1 != null) {
array1[lineNum] = line1;
}
if (line1 != null) {
array2[lineNum] = line2;
}
line1 = reader1.readLine();
line2 = reader2.readLine();
lineNum++;
}
if (areEqual) {
System.out.println("Same content.");
} else {
System.out.println("different content");
}
reader1.close();
reader2.close();
You can simply try above code.
Here I had used only WHILE loop, BufferedReader and FileReader.
The method is to return an array counting the number of lines, words and characters in a document. After running it through a test file I am still receiving some errors.
public static int[] wc(Reader in) throws IOException {
int data = in.read();
int charcounter = 0;
int linecounter = 0;
int wordcounter = 0;
boolean previouswhitespace = false;
while (data != -1){
if (((char) data == '\n')){
linecounter++;
}
if (!(Character.isWhitespace((char) data))){
charcounter++;
if ((previouswhitespace == true) || (wordcounter == 0)){
previouswhitespace = false;
wordcounter++;
}
}
else if ((Character.isWhitespace((char) data))){
previouswhitespace = true;
}
data = in.read();
}
int[] array = {linecounter, wordcounter, charcounter};
return array;
}
//To choose the file
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
String file_path = file.getAbsolutePath();
char[] c;
String [] words;
int charCounter = 0 ,wordsCounter = 0, lineCounter = 0;
//try and catch for the BufferedReader
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader(file_path));
while( (line = reader.readLine()) !=null){
c = line.replace(" ","").toCharArray();
charCounter+=c.length;
words = line.split(" ");
wordsCounter+=words.length;
lineCounter++;
}
}catch(Exception e){
// Handle the Exception
}
int array[] = {charCounter , wordsCounter, lineCounter};
Hope this is helping you!
I have to read data from file Here is data and want plot a graph vs thick(column 1 in data) and alpha(column 3) for every model. Every model has 7 line data,the last that start with 0 not required. Here is my code. it works but i don't think it is good code.please, suggest me better way to do the same.
public class readFile {
public static int showLines(String fileName) {
String line;
int currentLineNo = 0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
//skipping the line that start with M, # and 0.
currentLineNo++;
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
return currentLineNo;
}
//Now we know the dimension of matrix, so storing data into matrix
public static void readData(String fileName,int numRow) {
String line;
String temp []=null;
String data [][]=new String[numRow][10];
int i=0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
temp=(line.trim().split("[.]"));
for (int j = 0; j<data[i].length; j++) {
data[i][j] =temp[j];
}
i++;
}
}
// Extract one column from 2d matrix
for (int j = 0; j <numRow; j=j+6) {
for (int j2=j; j2 <6+j; j2++) {
System.out.println(Double.parseDouble(data[j2][0])+"\t"+Double.parseDouble(data[j2][2]));
//6 element of every model, col1 and col3
// will add to dataset.
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
}
//Main Method
public static void main(String[] args) {
//System.out.println(showLines("rf.txt"));
readData("rf.txt",showLines("rf.txt") );
}
}
as johnchen902 implies use a list
List<String> input=new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
input.add(line);
}
br.close();
int N=input.get(0).split(",").size(); // here add your delimiter
int M=input.size();
String[][] data=new String[M][N]
for (int i=0;i<M;i++){
String[] parts = string.split("-");
for (int k=0;k<n;k++){
data[i][k]=parts[k];
}
}
something like that
hope it helps. plz put more effort into asking the question. Give us the needed Input files, and the Code you came up with until now to solve the problem yourself.
A simple data file which contains
1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score,
losing score, crowd
I know how to store a data into an array and use the delimiter, but I am not exactly sure how to store EACH data item by a comma into separate arrays? Some suggestions and what particular code to be used would be nice.
UPDATE:
I just added the code but it still didn't work. Here's the code:
import java.io.*;
import java.util.Scanner;
public class GrandFinal {
public static Scanner file;
public static String[] array = new String[1000];
public static void main(String[] args) throws FileNotFoundException {
File myfile = new File("NRLdata.txt");
file = new Scanner (myfile);
Scanner s = file.useDelimiter(",");
int i = 0;
while (s.hasNext()) {
i++;
array[i] = s.next();
}
for(int j=0; j<array.length; j++) {
if(array[j] == null)
;
else if(array[j].contains("Y"))
System.out.println(array[j] + " ");
}
}
}
Here you go. Use ArrayList. Its dynamic and convenient.
BufferedReader br = null;
ArrayList<String> al = new ArrayList();
String line = "";
try {
br = new BufferedReader(new FileReader("NRLdata.txt"));
while ((line = br.readLine()) != null) {
al.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
What does not work in your case ?
Because your season array is empty. You need to define the length, for ex:
private static String[] season = new String[5];
This is not right because you don't know how many lines you are going to store. Which is why I suggested you to Use ArrayList.
After working around a bit, I have come up with following code:
private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;
public static void main(String[] args) {
try {
file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
counterReader = new BufferedReader(new FileReader(file));
int numberOfLine = 0;
String line = null;
try {
while ((line = counterReader.readLine()) != null) {
numberOfLine++;
}
String[][] storeAnswer = new String[9][numberOfLine];
int counter = 0;
fileReader = new BufferedReader(new FileReader(file));
while ((line = fileReader.readLine()) != null) {
String[] temp = line.split(",");
for (int j = 0; j < temp.length; j++) {
storeAnswer[j][counter] = temp[j];
System.out.println(storeAnswer[j][counter]);
}
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
I have added counterReader and fileReader; which are used for counting number of lines and then reading the actual lines. The storeAnswer 2d array contains the information you need.
I hope the answer is better now.
I am trying to add almost 2lac lines in particular txt file(actually conf file) by java program. But it takes almost 112 min when number is only 189000!
I write following code for that
import java.io.*;
public class Fileshandling_example {
static long s1;
static long e1;
static long e2;
static Fileshandling_example fhe= new Fileshandling_example();
public static void main(String args[]) {
try {
s1 = System.nanoTime();
File file1 = new File("\example\mandar.txt");
LineNumberReader lnr1 = new LineNumberReader(new FileReader(file1));
BufferedReader br1 = new BufferedReader(new FileReader(file1));
lnr1.skip(Long.MAX_VALUE);
int a = 1;
StringBuffer sb1 = new StringBuffer("[stations]");
String sCurrentline1 = br1.readLine();
while ((sCurrentline1 = br1.readLine()) != null) {
a++;
if (sCurrentline1.contentEquals(sb1) == true) {
int count = a;
int arraycount = 100000;
for(int i =0; i< (arraycount+1); i++){
if(0 == (i%10000)){
e2 = System.nanoTime();
System.out.println("Time = "+(e2-s1));
}
String abc ="extern => 00"+(1000 + (arraycount-i))+",1,Wait(0.05)";
fhe.insertintoExtensions(file1, (count+1),abc);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
e1 = System.nanoTime();
System.out.println("Time = "+(e1-s1));
}
public void insertintoExtensions(File inFile1, int lineno, String s1)throws Exception {
File outFile1 = new File("\example\111.tmp");
FileInputStream fis = new FileInputStream(inFile1);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile1);
PrintWriter out = new PrintWriter(fos);
String thisLine = "";
int i =1;
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(s1);
out.println(thisLine);
i++;
}
out.flush();
out.close();
in.close();
inFile1.delete();
outFile1.renameTo(inFile1);
}
}
Can any one help me where i get wrong?
I asked similar question coderanch but here i get clue very fast so i ask here also.
Sorry for that (cross forum asking).
Thanks.
You are loop 100,000 times for every '[stations]' found on "\example\mandar.txt":
if (sCurrentline1.contentEquals(sb1) == true) {
int count = a;
int arraycount = 100000;
for(int i =0; i< (arraycount+1); i++){
and call fhe.insertintoExtensions which loops "\example\mandar.txt" again to copy or the content of the line or the content of s1 parameter until the actual line number is reached:
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(s1);
out.println(thisLine);
i++;
}
Try to improve you code and use BufferedWriter instead of PrintWriter.