Error in reading from a file - java

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

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();

How to access a textfile entering its name in console? JAVA

What should one change in the code so that instead of entering a string in console, one enters a text name (exmple.txt) to get to the text (where the frequences will be counted)?
import java.io.*;
class FrequencyCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Enter the Text: ");
String s = br.readLine();
System.out.println ("Enter suffix: ");
String sub = br.readLine();
int ind,count = 0;
for(int i = 0; i + sub.length() <= s.length(); i++)
{
ind = s.indexOf(sub, i);
if (ind >= 0)
{
count++;
i = ind;
ind = -1;
}
}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}
}
First of I will refactor your code like this in order to reuse the calculateOcurrences method. Then I would read the text file line by line and sum all the occurrences by line.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Enter the file path: ");
final String filePath = br.readLine();
System.out.println ("Enter suffix: ");
final String suffix = br.readLine();
int count = 0;
Path path = FileSystems.getDefault().getPath(filePath);
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
count = count + calculateOcurrences(line,suffix);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
System.out.println("Occurence of '"+suffix+"' in String is "+count);
}
public static int calculateOcurrences(final String text, final String suffix) {
int ocurrences = 0;
for(int i = 0; i + suffix.length() <= text.length(); i++)
{
int indexOfOcurrence = text.indexOf(suffix, i);
if (indexOfOcurrence >= 0)
{
ocurrences++;
i = indexOfOcurrence;
}
}
return ocurrences;
}
}

Read from source file and split the contents into two other separate files

My goal is that I wish to read from a file with the name "input.txt", which has 10 lines of text, and then write 5 lines from the original into two other files with the names "test1.txt" and "test2.txt". I'm using the following code, but it is not working - please help me.
import java.util.Scanner;
import java.io.*;
public class main {
public static void main (String args[]) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader (new FileReader("bin/input.txt"));
File file = new File("bin/test2.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter("bin/test.txt"));
Scanner sc = new Scanner (br);
int i = 0;
while (sc.hasNextLine()){
sc.nextLine();
i++;
System.out.print(i);
int n = (i+1)/2;
System.out.print("\n"+n);
writer.write(sc.nextLine().toString());
writer.newLine();
if (n==5){
writer.close();
}
}
if (sc != null){
sc.close();
}
}
}
this will read from single file and splitting content into two file.
int count = 0;
BufferedReader br = null;
FileWriter fileWriter1 = new FileWriter("G:\\test1.txt");
FileWriter fileWriter2 = new FileWriter("G:\\test2.txt");
try {
String currentLine;
br = new BufferedReader(new FileReader("G:\\input.txt"));
while ((currentLine = br.readLine()) != null) {
count++;
if (count <= 5) {
fileWriter1.write(currentLine + "\n");
} else {
fileWriter2.write(currentLine + "\n");
}
}
} finally {
if (br != null) {
br.close();
}
fileWriter1.close();
fileWriter2.close();
}
Create two BufferedWriter instead of one with two files and then follow the below procedure:
count <- 0
while scanner hasNextLine
do
string line <- scanner's next Line
if (count > 4) {
writer2.write line
} else {
writer1.write line
}
count <- count + 1
done
finally close all three resources.

How do you input a line into a array separated as array elements?(Java)

Using a scanner to read a line of input. I thought there was a way to directly insert the line into an array and have it separate into string elements (divided by spaces).
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numberOfStudents = input.nextInt();
input.nextLine();
String[][] partners = new String[2][numberOfStudents];
partners[1] = input.nextLine();
}
}
I attempted to rewrite your code to possibly be what you want. Could you try to specify exactly what you're trying to do?
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numberOfStudents = input.nextInt();
//input.nextLine();
String[][] partners = new String[2][numberOfStudents];
for(int i=0; i<numberOfStudents; i++)
{
partners[1][i] = input.nextLine();
}
}
}
I think you're looking for split.
For example:
String val="I am a String";
String [] tabDelimitedVals=val.split(" ");
This is seen in the stack overflow post here:
How to split a string in Java
To read from a file, you can use
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
The above was taken from: Reading a plain text file in Java
Together, you can do:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
String val=br.readLine();
String [] splitted=val.split(" ");
}
finally {
br.close();
}

Count number of * from text file

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

Categories