I want to read a .txt file via a Java program.
Say this is the text file input.txt
abc, test, 1,2,3
abc
abcd
test, 1, 2, 3
Each line represents a row, each comma-separated value represents a column.
Currently my code is:
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
int num = readLines(); //this function just returns the number of lines
for (int i = 0; i < num; i++){
textData[i] = br.readLine();
}
br.close();
This outputs the text file as it was shown above if I print the array. But I require to insert into the array split by comma(could be other character as well, just use comma for now). So this means the output will be such that [abc,test,1,2,3],[abc],[abcd],[test,1,2,3] in the array. How should I proceed?
Thanks for the reply. Update:
Since i got my txt file into a array list,
[abc,test,1,2,3]
[abc]
[abcd]
[test,1,2,3]
How do i find the number of elements in each line?
Create an array list of array lists:
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
int lineCount = readLines();
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>(lineCount);
for (int i = 0; i < lineCount; i++) {
ArrayList<String> row = new ArrayList<String>();
String line = br.readLine();
for(String s: line.split(",")) {
row.add(s);
}
rows.add(row);
}
br.close();
Related
I'm trying to read a text file and put each comma separated value in an array and put all of them inside a 2d array.But the code I have right now puts the whole line in the array
Scanner sc = new Scanner(new BufferedReader(new FileReader(path)));
int rows = 3;
int columns = 1;
String[][] myArray = new String[rows][columns];
while (sc.hasNextLine()) {
for (int i = 0; i < myArray.length; i++) {
String[] line = sc.nextLine().trim().split(" " + ",");
for (int j = 0; j < line.length; j++) {
myArray[i][j] = line[j];
}
}
}
System.out.println(Arrays.deepToString(myArray));
This is the text file:
A6,A7
F2,F3
F6,G6
Output
[[A6,A7], [F2,F3], [F6,G6]]
Expected Output
[[A6],[A7],[F2],[F3],[F6],[G6]]
The problem is that you are assigning the entire 2D array instead of just each item.
Here are several alternatives.
Use Files.lines to stream the file.
splitting on a comma creates the 1D array of two elements for each line
flatMap that to stream each item.
that map that to an array of one item.
then just store them in a 2D array.
String[][] array = null;
try {
array = Files.lines(Path.of("f:/MyInfo.txt"))
.flatMap(line->Arrays.stream(line.split(","))
.map(item->new String[]{item}))
.toArray(String[][]::new);
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (array != null) {
System.out.println(Arrays.deepToString(array));
}
prints
[[A6], [A7], [F2], [F3], [F6], [G6]]
Here is an approach similar to yours.
List<String[]> list = new ArrayList<>();
try {
Scanner scanner = new Scanner(new File("f:/MyInfo.txt"));
while (scanner.hasNextLine()) {
String[] arr = scanner.nextLine().split(",");
for (String item : arr) {
list.add(new String[]{item});
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
There is no deepToString for Lists so you either iterate it or convert to a 2D array.
String[][] ar = list.toArray(String[][]::new);
System.out.println(Arrays.deepToString(ar));
prints
[[A6], [A7], [F2], [F3], [F6], [G6]]
i think you have to double the rows size and for each line just put one element and increment the i++
The declaration of the result array is not correct.
Since you want the end result should look like this, [[A6],[A7],[F2],[F3],[F6],[G6]], it is a 2-dimensional array with one row and six columns.
Considering it, I have changed and simplified your code.
int rows = 3;
String[][] r = new String[1][rows * 2];
FileInputStream fstream = new FileInputStream("/path/to/the/file")
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while((line = br.readLine()) != null) {
String[] current = line.split(",");
r[0][i++] = current[0];
r[0][i++] = current[1];
}
I have a .txt file with 300 rows and 785 columns with a bunch of numbers in E notation (e.g. -6.431571950262252035e-02). How would I covert those numbers into a 2-D array?
This is all I have:
double[][] hiddenArray = new double[300][785];
Scanner scanner = new Scanner(System.in) ;
String hiddenFile = "hidden-weights.txt";
String outputFile = "output-weights.txt";
scanner.close();
Scanner in = new Scanner(new File(hiddenFile));
String hidden= in.nextLine();
Use Scanner::hasNext() to loop while there are more lines and Scanner::nextLine() to fetch the next line, then use String::split() to get an array of strings on each line (Note: my presumption is that the columns are separated by commas (i.e. ,) but feel free to adjust for your needs). For parsing the numbers in e notation, use Double.valueof(), and add that value to the array (e.g. hiddenArray).
You should be able to use the sample below. I also created an example on tutorialspoint.com codingGround but that may not work...
try {
String delimiter = ","; //separates columns - change for your needs
int row = 0;
Scanner in = new Scanner(new File(hiddenFile));
String line;
while (in.hasNext() && (line = in.nextLine()) != null ) {
String[] vals = line.trim().split(",");
for (int col = 0; col < vals.length; col++) {
hiddenArray[row][col] = Double.valueOf(vals[col]);
}
row++;
}
}
catch(FileNotFoundException e) {
System.out.println("file not found - "+e.getMessage());
}
I'm new to OOP, but I'm trying to create my first bigger program.
I've read a txt-file and stored the values (doubles) into an array, I call it originalArray. The text has two columns and 20 lines. So when I want to print the values in the first column of the txt-file I simply write:
System.out.println(originalArray[0]);
OUTPUT: 1991.00
300.50
498.50 .... et cetera...
My problem is that i'd like to use a for-loop (or whatever) to create two new arrays, each consisting one column from the "original array".
I thought it would be as simple as using a for-loop, like this;
double [] newArray = new double [20];
for(int i = 0; i < originalArray.length; i++){
newArray[i] = originalArray[0] //if I want to fill it with the first
//columns data... the second would be newArray2[i] = originalArray[1]
}
But this fills the new array with ONE element from the column in the originalArray... So - I need help to figure of how to write the loop to fill the new arrays with all elements from one chosen column.
Very grateful for help!
Regards/ frustrated newbie
EDIT: This is how I read the txt file:
String file = "C:\\Users\\komena\\Desktop\\30th-sales.csv";
BufferedReader br = null;
String line = "";
String splitBy = ";";
originalArray = new double [20];
br = new BufferedReader(new FileReader(file));
br.readLine();//skip the first line to get rid of header…
while ((line = br.readLine()) != null) {
String[] readlineArray = line.split(splitBy);
for (int i = 0; i < readlineArray.length; i++) {
originalArray[i] = Double.parseDouble(readlineArray[i]);
}
Whole text (csv) file:
300.50;330.00
489.50;296.50
34.50;399.50
900.00;1890.00
2052.00;568.00
354.00;0.00
399.00;0.00
1299.50;0.00
426.00;259.00
29.50;2300.50
99.50;349.50
2500.50;0.00
358.50;113.00
789.00;239.50
998.00;348.00
16.50;679.00
800.00;723.00
1899.50;950.50
550.50;568.00
Create the new 2D array with the size of the 1st dimension the same as the originalArray's length and the 2nd dimension the size of 2 (2 columns). Then simply loop it and add the old values to one column and also the new ones if reuqired, otherwise they will be set as 0.0 defaultly.
double originalArray[] = {1991.00, 300.50, 498.50};
double newArray[][] = new double[originalArray.length][2];
for (int i=0; i<originalArray.length; i++) {
newArray[i][0] = i // Fill the 1st column with sth like ID
newArray[i][1] = originalArray[i]; // Copy the 1D array to the 2nd column
}
System.out.println(Arrays.deepToString(newArray)); // Print all the array values
Output:
[[1.0, 1991.00],
[2.0, 300.50],
[3.0, 498.50]]
Moreover you read the file wrong. Notice that you have 2 values in the each line separated with ; and lines separated with \n. So read the line by line and add 2 values to the array.
The i variable represents the actual index of the originalArray[].
BufferedReader br = null;
String line = "";
int i=0;
double originalArray[] = new double[20];
br = new BufferedReader(new FileReader(file));
br.readLine();//skip the first line to get rid of header…
while ((line = br.readLine()) != null && i<originalArray.length) {
String[] readlineArray = line.split(";");
originalArray[i] = Double.parseDouble(readlineArray[0]);
originalArray[i+1] = Double.parseDouble(readlineArray[1]);
i+=2;
}
System.out.println(Arrays.toString(originalArray));
I wrote a small Java program that reads the data from CSV file and I have to save these values in 2 dimensional array. Now I need to write these values (not all information will be stored because the array contains many redundant data) from this array to a new CSV file. Can anyone help me with a code sample, I searched a lot but could not find an answer. My code is:
int row = 0;
int col = 0;
String[][] numbers=new String[24][24];
File file = new File("D:\\thesis\\sorted_file.csv");
if(file.exists())
{
System.out.println("file exist");
}
BufferedReader bufRdr;
bufRdr = new BufferedReader(new FileReader(file));
String line = null;
String delims=",";
//read each line of text file
while((line = bufRdr.readLine()) != null )
{
StringTokenizer st = new StringTokenizer(line,delims);
col=0;
while (st.hasMoreTokens())
{
//get next token and store it in the array
numbers[row][col] = st.nextToken();
System.out.print("number["+row+"]["+col+"]:"+numbers[row][col]);
col++;
}
row++;
}
You can use something like this...
BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
StringBuilder sb = new StringBuilder();
for (String element : numbers) {
sb.append(element);
sb.append(",");
}
br.write(sb.toString);
br.close();
I'm trying to read a text file with this format:
Array x
1,3,5,4
Array y
12,13,15,11
and put it in two array, but I only want the integer.
What delimiter should I use to ignore the String and the empty line?
Here's my code in putting the int to arrays. By the way, I'm using scanner to read the file:
Scanner sc = null;
try
{
sc = new Scanner(new FileInputStream("C:\\x.txt"));
sc.useDelimiter(""); // What will I put inside a quote to get only the int values?
}
catch(Exception e)
{
System.out.println("file not found!");
}
int[] xArray = new int[4];
int[] yArray = new int[4];
while (sc.hasNextInt( )){
for(int i=0; i<4; i++){
xArray[i] = sc.nextInt( );
}
for(int i=0; i<4; i++){
yArray[i] = sc.nextInt( );
}
}
What I want to get is
int[] xArray = {1,3,5,4}
int[] yArray = {12,13,15,11}
I hope you understand :)
Thanks.
I suggest you to use bufferedreader instead of scanner. You can use below code :
BufferedReader br=new BufferedReader(new FileReader("your file name"));
br.readLine(); //it will omit first line Array x
String x=br.readLine(); //it return second line as a string
String[] x_value=x.split(","); //You can parse string array into int.
This is for Array x. You can do the same for array y. and after that parse into int.