Count number of * from text file - java

I have this code to count the number of * from a string entered. but I need to find it from an text file. Any idea?
import java.lang.String;
import java.io.*;
import java.util.*;
public class CountStars {
public static void main(String args[]) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String:");
String text = bf.readLine();
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c=='*' ) {
count++;
}
}
System.out.println("The number of stars in the given sentence are " + count);
}
}

Use a FileInputStream and a InputStreamReader together, while specifying the character-encoding. "UTF-8" is a pretty safe bet. Then read each line and count the number of '*' characters as you already did. Then create a grand total and don't forget to close the file afterwards.

We can write something as simple as below:
int count= 0;
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String text;
while((text= br.readLine()) != null) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c=='*' ) {
count++;
}
}
}
System.out.println("Count Stars = "+ count);

Replace BufferedReader line with below lines.
Path path = Paths.get(aFileName);
BufferedReader bf = Files.newBufferedReader(path, ENCODING)
where aFileName is the file path, you can either use args or make a function.
Update1:
Thanks owlstead.
Use following line if version < 7.
BufferedReader bf = new BufferedReader (new FileReader (aFileName));
Regards,
Tamour

Related

How to read a String from a txt file and store it into a char array java

So I am trying to read a txt file into a char array and print out the contents, but I only get the first index of the String to print out. The contents of the file are "EADBC"
public static void main(String args[]) throws IOException
{
char [] correctAnswers = new char [20];
String [] studentName = new String[5];
char [][] studentAnswers = new char [20][20];
Scanner sc = new Scanner (System.in);
System.out.println ("Welcome to the Quiz Grading System \n");
System.out.println ("Please Enter the name of the file that contains the correct answers");
Scanner answerFile = new Scanner (new File (sc.next() + ".txt"));
int i = 0;
int fillLvl = 0;
String answer;
while (answerFile.hasNext() )
{
answer = answerFile.next();
correctAnswers[i] = answer.charAt(i);
i++;
fillLvl = i;
}
answerFile.close();
System.out.println("Correct Answers: ");
for(int j = 0; j < fillLvl; j++)
{
System.out.println(correctAnswers[j]);
}
To read from a text file and convert into an array:
File file = new File("C:\\Users\\dell\\Desktop\\rp.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
char[] string1={};
int size = 0;
//reads the string and converts into array
while ((st = br.readLine()) != null){
string1 = st.toCharArray();
size = st.length();
}
//For printing
for(int i=0;i<size;i++){
System.out.println(string1[i]);
}
Inside while loop use like this..
while (answerFile.hasNext() )
{
answer = answerFile.next();
int j = 0;
while(answer != null && !answer.isEmpty() && j < answer.length()){
correctAnswers[i] = answer.charAt(j);
i++;
j++;
fillLvl = i;
}
}
It is always recommended to use FileReader, BufferedReader to perform file operation;
Here you go, read once and print them simple. Don't read them into a string and split them and again to a char.
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("\\path\\to\\file.extension"))
);
int c;
while((c = reader.read()) != -1) {
char character = (char) c;
System.out.println(character);
}
reader.close();

Why does my summation program throw a NumberFormatException?

I want to read the numbers from the file and sum up the total, but I cannot seem to process the data properly. It is successfully outputting the numbers but is not successfully summing them up.
My code:
import java.io.*;
import java.util.*;
public class Q1 {
public static void main(String[] args) throws IOException {
StringBuffer str = new StringBuffer();
FileWriter output = new FileWriter("number.txt");
Random r = new Random();
for (int i = 1; i < 101; i++) {
str.append(r.nextInt(100) + " ");
}
output.write(str.toString());
System.out.println(str.toString());
output.close();
FileReader reader = new FileReader("number.txt");
BufferedReader input = new BufferedReader(reader);
String line = input.readLine();
int total = 0;
while (line != null) {
System.out.print(line);
total += Integer.parseInt(input.readLine());
}
System.out.println(total);
}
}
And the stacktrace:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Q1.main(Q1.java:42)
You don't append a ending line char to the output.
Try out this snippet:
StringBuffer str = new StringBuffer();
FileWriter output = new FileWriter("number.txt");
Random r = new Random();
for (int i = 1; i < 101; i++) {
str.append(r.nextInt(100)).append('\n');
}
output.write(str.toString());
System.out.println(str.toString());
output.close();
FileReader reader = new FileReader("number.txt");
BufferedReader input = new BufferedReader(reader);
String line;
int total = 0;
while ((line = input.readLine())!=null) {
total += Integer.parseInt(line);
}
System.out.println(total);
If the output looks weird, examine where the output is being created. That is usually where you will find the problem. Also added in some small changes to give you an idea of a different way you could go about it that might make your life easier.

Error in reading from a file

In the following program, I get input from console and store the odd number of characters and even number of characters in a separate file. But when I run the program, I get only one character.
For example, if I give Hello as input and if I read from the even file, it displays only 'o'.
import java.io.*;
import java.util.*;
class OddEvenFile
{
public static void main(String args[])throws IOException
{
char tmp;
String str;
StringBuffer rese=new StringBuffer();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FileInputStream fine=new FileInputStream("C:\\Users\\Siva\\Documents\\Java\\Even.txt");
FileInputStream fino=new FileInputStream("C:\\Users\\Siva\\Documents\\Java\\Odd.txt");
FileOutputStream foute=new FileOutputStream("C:\\Users\\Siva\\Documents\\Java\\Even.txt");
FileOutputStream fouto=new FileOutputStream("C:\\Users\\Siva\\Documents\\Java\\Odd.txt");
System.out.print("\nEnter a String :");
str=br.readLine();
System.out.print("\n Length :"+str.length());
for(int i=1;i<str.length();i++)
{
char c=str.charAt(i);
if(i%2 == 0)
foute.write(c);
else
fouto.write(c);
}
while(fine.read()!=-1)
{
tmp=(char)fine.read();
//tmp=String.valueOf()
rese.append(tmp);
}
System.out.print("In even file :"+(rese.toString()));
}
}
Try this: First write to the files, then close the files, and then open the new files:
public static void main(String args[])throws IOException
{
char tmp;
String str;
StringBuffer rese=new StringBuffer();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FileOutputStream foute=new FileOutputStream("Even.txt");
FileOutputStream fouto=new FileOutputStream("Odd.txt");
System.out.print("\nEnter a String :");
str=br.readLine();
System.out.print("\n Length : "+str.length() + "\n");
for(int i = 0;i < str.length(); i++)
{
char c=str.charAt(i);
if(i%2 == 0)
foute.write(c);
else
fouto.write(c);
}
foute.close();
fouto.close();
FileInputStream fine=new FileInputStream("Even.txt");
FileInputStream fino=new FileInputStream("Odd.txt");
String s = "";
while(fine.available() > 0)
{
s += (char) fine.read();
}
fine.close();
fino.close();
System.out.print("In even file : " + s);
}

Find a specific line of a text file (not by line_number) and store it as a new String

I am trying to read a text file in java using FileReader and BufferedReader classes. Following an online tutorial I made two classes, one called ReadFile and one FileData.
Then I tried to extract a small part of the text file (i.e. between lines "ENTITIES" and "ENDSEC"). Finally l would like to tell the program to find a specific line between the above-mentioned and store it as an Xvalue, which I could use later.
I am really struggling to figure out how to do the last part...any help would be very much apprciated!
//FileData Class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main (String[] args) throws IOException {
String file_name = "C:/Point.txt";
try {
ReadFile file = new ReadFile (file_name);
String[] aryLines = file.OpenFile();
int i;
for ( i=0; i < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
}
catch (IOException e) {
System.out.println(e.getMessage() );
}
}
}
// ReadFile Class
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.lang.String;
public class ReadFile {
private String path;
public ReadFile (String file_path) {
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader (path);
BufferedReader textReader = new BufferedReader (fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
String nextline = "";
int i;
// String Xvalue;
for (i=0; i < numberOfLines; i++) {
String oneline = textReader.readLine();
int j = 0;
if (oneline.equals("ENTITIES")) {
nextline = oneline;
System.out.println(oneline);
while (!nextline.equals("ENDSEC")) {
nextline = textReader.readLine();
textData[j] = nextline;
// xvalue = ..........
j = j + 1;
i = i+1;
}
}
//textData[i] = textReader.readLine();
}
textReader.close( );
return textData;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader (path);
BufferedReader bf = new BufferedReader (file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine()) != null ) {
numberOfLines ++;
}
bf.close ();
return numberOfLines;
}
}
I don't know what line you are specifically looking for but here are a few methods you might want to use to do such operation:
private static String START_LINE = "ENTITIES";
private static String END_LINE = "ENDSEC";
public static List<String> getSpecificLines(Srting filename) throws IOException{
List<String> specificLines = new LinkedList<String>();
Scanner sc = null;
try {
boolean foundStartLine = false;
boolean foundEndLine = false;
sc = new Scanner(new BufferedReader(new FileReader(filename)));
while (!foundEndLine && sc.hasNext()) {
String line = sc.nextLine();
foundStartLine = foundStartLine || line.equals(START_LINE);
foundEndLine = foundEndLine || line.equals(END_LINE);
if(foundStartLine && !foundEndLine){
specificLines.add(line);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return specificLines;
}
public static String getSpecificLine(List<String> specificLines){
for(String line : specificLines){
if(isSpecific(line)){
return line;
}
}
return null;
}
public static boolean isSpecific(String line){
// What makes the String special??
}
When I get it right you want to store every line between ENTITIES and ENDSEC?
If yes you could simply define a StringBuffer and append everything which is in between these to keywords.
// This could you would put outside the while loop
StringBuffer xValues = new StringBuffer();
// This would be in the while loop and you append all the lines in the buffer
xValues.append(nextline);
If you want to store more specific data in between these to keywords then you probably need to work with Regular Expressions and get out the data you need and put it into a designed DataStructure (A class you've defined by our own).
And btw. I think you could read the file much easier with the following code:
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
...
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
Then you don't have to read first how many lines the file has. You just start reading till the end :).
EDIT:
I still don't know if I understand that right. So if ENTITIES POINT 10 1333.888 20 333.5555 ENDSEC is one line then you could work with the split(" ") Method.
Let me explain with an example:
String line = "";
String[] parts = line.split(" ");
float xValue = parts[2]; // would store 10
float yValue = parts[3]; // would store 1333.888
float zValue = parts[4]; // would store 20
float ... = parts[5]; // would store 333.5555
EDIT2:
Or is every point (x, y, ..) on another line?!
So the file content is like that:
ENTITIES POINT
10
1333.888 // <-- you want this one as xValue
20
333.5555 // <-- and this one as yvalue?
ENDSEC
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
// read next line
line = reader.readLine();
if(line.equals("10") {
// read next line to get the value
line = reader.readLine(); // read next line to get the value
float xValue = Float.parseFloat(line);
}
line = reader.readLine();
if(line.equals("20") {
// read next line to get the value
line = reader.readLine();
float yValue = Float.parseFloaT(line);
}
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
If you have several ENTITIES in the file you need to create a class which stores the xValue, yValue or you could use the Point class. Then you would create an ArrayList of these Points and just append them..

Counting the number of characters from a text file

I currently have the following code:
public class Count {
public static void countChar() throws FileNotFoundException {
Scanner scannerFile = null;
try {
scannerFile = new Scanner(new File("file"));
} catch (FileNotFoundException e) {
}
int starNumber = 0; // number of *'s
while (scannerFile.hasNext()) {
String character = scannerFile.next();
int index =0;
char star = '*';
while(index<character.length()) {
if(character.charAt(index)==star){
starNumber++;
}
index++;
}
System.out.println(starNumber);
}
}
I'm trying to find out how many times a * occurs in a textfile. For example given a text file containing
Hi * My * name *
the method should return with 3
Currently what happens is with the above example the method would return:
0
1
1
2
2
3
Thanks in advance.
Use Apache commons-io to read the file into a String
String org.apache.commons.io.FileUtils.readFileToString(File file);
And then, use Apache commons-lang to count the matches of *:
int org.apache.commons.lang.StringUtils.countMatches(String str, String sub)
Result:
int count = StringUtils.countMatches(FileUtils.readFileToString(file), "*");
http://commons.apache.org/io/
http://commons.apache.org/lang/
Everything in your method works fine, except that you print the count per line:
while (scannerFile.hasNext()) {
String character = scannerFile.next();
int index =0;
char star = '*';
while(index<character.length()) {
if(character.charAt(index)==star){
starNumber++;
}
index++;
}
/* PRINTS the result for each line!!! */
System.out.println(starNumber);
}
int countStars(String fileName) throws IOException {
FileReader fileReader = new FileReader(fileName);
char[] cbuf = new char[1];
int n = 0;
while(fileReader.read(cbuf)) {
if(cbuf[0] == '*') {
n++;
}
}
fileReader.close();
return n;
}
I would stick to the Java libraries at this point, then use other libraries (such as the commons libraries) as you become more familiar with the core Java API. This is off the top of my head, might need to be tweaked to run.
StringBuilder sb = new StringBuilder();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
while (s != null)
{
sb.append(s);
s = br.readLine();
}
br.close(); // this closes the underlying reader so no need for fr.close()
String fileAsStr = sb.toString();
int count = 0;
int idx = fileAsStr('*')
while (idx > -1)
{
count++;
idx = fileAsStr('*', idx+1);
}

Categories