I have a file in this format:
0 2 4
3 2 4
3 5 2
1 8 2
My aim is to read the first line on each file and store it in a array. So at the end I should have 0,3,3,1
I thought one approach would be, read the line until we encounter a space and save that in a array...but it would keep on reading 2 and 4 after
Is there a efficient way of doing this, my cod is shown below:
openandprint()
{
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader("final.txt")))
{
String line;
while ((line = br.readLine()) != null) {
int change2Int=Integer.parseInt(line.trim());
figures [i] = change2Int;
i++;
}
}
catch (Exception expe)
{
expe.printStackTrace();
}
}
Using a Scanner would make the code considerably cleaner:
private static openandprint() throws IOException {
int i = 0;
try (Scanner s = new Scanner("final.txt"))) {
String line;
while (s.hasNextLine()) {
int change2Int = s.nextInt();
s.nextLine(); // ignore the rest of the line
figures [i] = change2Int;
i++;
}
}
}
Try
int change2Int=Integer.parseInt((line.trim()).charAt(0)-'0');
or
int change2Int=Character.getNumericValue(line.charAt(0));
with your approch you are reading the whole line and parsing it to int which will give you NumberFormatException because of the space between the digits.
BufferedReader br = ...;
String line = null;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" ");
int next = Integer.parseInt(parts[0]);
System.out.println("next: " + next);
}
Related
I have different text files I would like to read, and I am using BufferedReader for it like this:
int theMax = 0;
int theTypes = 0;
int []theSlices = {};
/*
INPUT1:
17 4
2 5 6 8
INPUT2:
100 10
4 14 15 18 29 32 36 82 95 95
*/
try {
FileReader reader = new FileReader("INPUT1.in");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println(numbers[0]);
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
;
My problem is that I would like to set the values for theMax, theTypes & theSlices but for that I need to get the current line number and I have no idea how to do that. Reading the file works and println(numbers[0] prints 17 and 2. I am kind of stuck here so I am happy for every help.
Example for INPUT1:
theMax = 17
theTypes = 4
theSlices = 2 5 6 8
Very simple: you keep track yourself.
String line;
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println("Linenumber " + currentLine);
System.out.println(numbers[0]);
System.out.println(line);
currentLine ++;
}
reader.close();
Not sure I totally understand what you are after, but for just keeping track of the line numbers, create a variable that you increment in your while loop
i.e.
try {
FileReader reader = new FileReader("INPUT1.in");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
long currentLineNr = 0;
while ((line = bufferedReader.readLine()) != null) {
currentLineNr++;
String[] numbers = line.split(" ");
System.out.println(numbers[0]);
System.out.println(line);
//Use the currentLineNr how you like
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
First of all, as far as I know (and having read the official Java documentation for it here - https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html), the BufferedReader class does not in itself give you a mechanism (e.g. a getCurrentLine() method) to determine the current line.
However, there is absolutely nothing stopping you from keeping track of current line number yourself through, say, a counter variable.
Therefore, the relevant section of your code would look like:
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
currentLine++;
String[] numbers = line.split(" ");
/* NOTE: this can be numbers.length >= 2 if you don't care to enforce
having exactly 2 numbers as the first line
*/
if(currentLine == 1 && numbers.length == 2) {
theMax = Integer.valueOf(numbers[0]);
theTypes = Integer.valueOf(numbers[1]);
} else {
for(int index = 0; index < numbers.length; index++) {
theSlices[index] = Integer.valueOf(numbers[index]);
}
}
}
// do something with read values
I would also like to mention that your code could be improved here and there, for example:
You can replace your try with a try-with-resources, such that your readers are managed/closed automatically even if an exception occurs.
If you decide not to use try-with-resources, then you'll need to move your reader.close() method call in a finally block, because if an exception actually occurs you are never closing your resource.
These 2 lines
FileReader reader = ;
BufferedReader bufferedReader = new BufferedReader(reader);
can be simplified into:
BufferedReader bufferedReader = new BufferedReader(new FileReader("INPUT1.in"));
and then you only need to manage the bufferedReader instance if sticking to try instead of try-with-resources.
Hope this helps.
PS: not saying that my code snippet above is perfect, I'm sure it can be written more cleanly
Use java.io.LineNumberReader.
LineNumberReader is a subclass of BufferedReader that keeps track of line numbers. It provides a getLineNumber() method for getting the current line number.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/LineNumberReader.html
Example:
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class Example {
public static void main(String[] args) throws IOException {
try (FileReader fr = new FileReader("input.txt");
LineNumberReader r = new LineNumberReader(fr)) {
String next;
while ((next = r.readLine()) != null) {
System.out.println("line number " + r.getLineNumber() + " = " + next);
}
}
}
}
I want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!
I am trying to compute the number of elements in a column present in a CSV file using which I would like to compute the mean.
This is how I tried to find the length of the column, but it gives me the length of each data in the column. It's something very silly but I have been stuck with this for a long time.
public static void main(String[] args) throws Exception {
String splitBy = ";";
int x;
BufferedReader br = new BufferedReader(new FileReader("bank.csv"));
String line;
while ((line = br.readLine()) !=null) {
String[] b = line.split(splitBy);
x = b[10].length();
System.out.println("length " + x);
}
br.close();
}
This is the CSV file:
https://raw.githubusercontent.com/pandutruhandito/practice_bank_marketing_data/master/bank/bank-full.csv
You will want something like the following. A few notes.
If a value is always required then you can simply count the number of lines in the CSV to give you the number of values in the column. Otherwise you'll need to check if there is an actual value.
You were grabbing the month column, remember indexes start at 0.
public static void main(String[] args) throws Exception {
final String splitBy = ";";
int totalValue = 0;
int columnCount = 0;
final BufferedReader br = new BufferedReader(new FileReader("C:/test/bank-full.csv"));
String line;
// Throw away headers.
line = br.readLine();
while ((line = br.readLine()) != null)
{
String[] splitCSV = line.split(splitBy);
if (!splitCSV[9].equals(""))
{
totalValue += Integer.parseInt(splitCSV[9]);
columnCount++;
}
}
br.close();
System.out.println("Average is " + totalValue / columnCount);
}
b[10].length() is incorrect: it gives you the size of string of the 10th element in a particular line (and it changes in the loop)
line.length(): lengh of the line
b.length: number of elements in a line
if you want the number of columns, you can just only keep the number of lines read (just count your readlin())
Or you can also keep everything in a table.
beware: some csv have , or ; , and perhaps inside " (if there is string)
You have to use x = b.length; which will give you exact length per line.
public static void main(String[] args) throws Exception {
String splitBy = ";";
int x;
BufferedReader br = new BufferedReader(new FileReader("bank.csv"));
String line;
while ((line = br.readLine()) !=null) {
String[] b = line.split(splitBy);
x = b.length;
System.out.println("length " + x);
}
br.close();
}
I am using eclipse ; I need to read integers from a text file that may have many lines of numbers separated by space : 71 57 99 ...
I need to get these numbers as 71 and 57 ...but my code produces numbers in the range 10 to 57
int size = 0;
int[] spect = null;
try {
InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
size = is.available();
spect = new int[size];
for (int si = 0; si < size; si++) {
spect[si] = (int) is.read();// System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print(e.getMessage());
}
read() reads single byte and then you are converting into int value, you need to read line by line using BufferedReader and then split() and Integer.parseInt()
Have you considered using a Scanner to do this? Scanner can take the name of the file as the parameter and can easily read out each individual number.
InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
int[] spect = new int[is.available()];
Scanner fileScanner = new Scanner("/dataset.txt");
for(int i = 0; fileScanner.hasNextInt(); i++){
spect[i] = fileScanner.nextInt();
}
You may convert it to a BufferedReader and read and split the lines.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while((line = br.readLine()) != null) {
String[] strings = line.split(" ");
for (String str : strings) {
Integer foo = Integer.parseInt(str);
//do what you need with the Integer
}
}
I have the sample.txt which contains 100 Integers (range 0-9) in every line formatted like this:
9 2 0 3 4 1 0 7 5 3 7 8 6 2 0 1 4 4 5 9 0 3 2 1 7 (etc... 100 numbers)
I want to scan the file and put every line into a 10x10 table. So:
public void loadTableFromFile(String filepath){
try (Scanner s = new Scanner(new BufferedReader(new FileReader(filepath)))) {
String line;
while (s.hasNextLine()) {
// WHAT HERE? THIS BLOCK DOES NOT WORK
/* if (s.hasNextInt()) {
//take int and put it in the table in the right position procedure
} else {
s.next();
} */
// END OF NOT WORKING BLOCK
}
} catch (FileNotFoundException e){
}
}
How about something like this?
public void loadTableFromFile(String filepath) {
Scanner s = null; // Our scanner.
try {
s = new Scanner(new BufferedReader(
new FileReader(filepath))); // get it from the file.
String line;
while (s.hasNextLine()) { // while we have lines.
line = s.nextLine(); // get a line.
StringTokenizer st = new StringTokenizer(line, " ");
int i = 0;
while (st.hasMoreTokens()) {
if (i != 0) {
System.out.print(' '); // add a space between elements.
}
System.out.print(st.nextToken().trim()); // print the next element.
i++;
if (i % 10 == 0) { // Add a new line every ten elements.
System.out.println();
}
}
System.out.println(); // between lines.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (s != null)
s.close();
}
}
Here is a solution that reads the line of the file into an array of strings using the split by whitespace method, and then reads them in using a for loop. I threw any exceptions that might have occurred in the method declaration, alternatively, use the try catch loop as above (might be better design, not sure about that.)
public void loadTableFromFile(String filePath) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String[] line = br.readLine().split(" ");
br.close(); // file only has 1 line with 100 integers
int[][] mydata = new int[10][10];
for(int i = 0; i < line.length; i++) {
mydata[i % 10][(int) (i / 10)] = Integer.parseInt(line[i]);
}
}
Now, if the file has more than one line, you could instead read the entire file line by line, and then use the above idea like this:
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line1;
while((line1 = br.readLine()) != null) {
String[] line = line1.split(" ");
... // do above stuff of reading in 1 line here
}
br.close();
Try,
try (Scanner s = new Scanner(new BufferedReader(new FileReader(filepath)))) {
String line;
while (s.hasNextLine()) {
String[] strArr=line.split(" ");
for(int i=0;i<strArr.length;i++){
System.out.print(" "+strArr[i]);
if((i+1)%10==0){
System.out.println();
}
}
}
} catch (FileNotFoundException e){
}