Reading input stream from file prints missing characters - java

I am using BufferedReader in java to read characters from an input file. However, the output is unusual. In my code below, I first use scanner to show the contents of the file itself then I use BufferedReader to print each individual character:
import java.util.Scanner;
import java.io.*;
//import java.io.File;
public class Inputs
{
public static void main(String[] args)
{
System.out.println("Inputs");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
System.out.println(input);
// Open the file
File file = new File("Simple.java");
try {
Scanner fileIn = new Scanner(file);
while(fileIn.hasNext()){
System.out.println(fileIn.next());
}
fileIn.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Simple.java");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
String character = Character.toString ((char) br.read());
System.out.println (character);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Below is the output I get, the first tokens displayed are by the scanner but after the highlighted prentices its the BufferedReaders output. It prints 3 spaces then a closed curly bracket then -1 (end). What is the meaning of this?

In your code you are reading the line in while loop condition with br.readline(). Then in the loop body you are again reading the char using br.read(). So the first character in the each line is printed.
while ((strLine = br.readLine()) != null) {
// Print the content on the console
String character = Character.toString ((char) br.read());
System.out.println (character);
}
To fix there either use the method metioned by Halko Sajtarevic(But there each char is read as an integer and converted back to string) or simply eliminate reading the character second time and just print the string.
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}

Your problem is that you are reading the BufferedReader line by line instead of character by character.
Try this version instead:
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Simple.java");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
char c;
while ((c = (char) br.read()) != (char) -1) {
// Print the content on the console
String character = Character.toString(c);
System.out.print(character);
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}

Related

How can I print the average of the lines in this file?

I'm writing a program in Java which iterates over each line of a text file, this text file contains numbers which are on a separate line, I have successfully made the program read each line and print them to a new file.
However I'm trying to print the average of these numbers to the new file as well, I understand that I would have to treat each line as a float or double (as I'm using decimal numbers) but I'm unsure of how to do this, this is what I've got so far.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Run {
public static void main(String[] args) throws Exception {
Write(); //call Write method
}
public static void Write() throws Exception {
String line, lineCut;
BufferedReader br = null; //initialise BR- reads text from file
BufferedWriter bw = null; //initialise BR- writes text to file
try
{
br = new BufferedReader(new FileReader("/Users/jbloggs/Documents/input.txt")); //input file
bw = new BufferedWriter(new FileWriter("/Users/jbloggs/Desktop/output.txt")); //output file
line = br.readLine(); // declare string equal to each line
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ","); // replace ; with ,
//lineCut = line.substring(1, line.length());
//int mynewLine = Integer.parseInt(lineCut);
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
System.out.println("success"); //print if program works
br.close();
bw.close();
}
catch(Exception e){
throw(e); // throw exception
}
}
}
Basically this is what you are doing
reading lines from a file
replacing ';' with a ','
writing this modified line to a new file
So in each of above operation, you have never treated the line to be a Number. To find average, you need to parse each line of number into real Number, Double.parseDouble("21.2") etc, and in each iteration, you know what to do :-)
For example:
double sum= 0;
int count = 0;
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ","); // replace ; with ,
//lineCut = line.substring(1, line.length());
int num = Double.parseDouble(lineCut);
sum = sum + num; count++;
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
br.write(String.valueOf(sum/count));
Not tested. I am considering each line has a number and nothing else. Remember your should check the valou on linecount to avoid an Exception during the conversion from String to float.
public static void Write() throws Exception {
String line, lineCut;
BufferedReader br = null; //initialise BR- reads text from file
BufferedWriter bw = null; //initialise BR- writes text to file
try
{
br = new BufferedReader(new FileReader("/Users/jbloggs/Documents/input.txt")); //input file
bw = new BufferedWriter(new FileWriter("/Users/jbloggs/Desktop/output.txt")); //output file
line = br.readLine(); // declare string equal to each line
float sum = 0;
int counter = 0;
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ",");
sum += Float.parseFloat(lineCut);
counter++;
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
bw.write("Average = ");
bw.write(sum / counter);
bw.write("\n");
System.out.println("success"); //print if program works
br.close();
bw.close();
}
catch(Exception e){
throw(e); // throw exception
}
}
}

BufferedReader/BufferedWriter Output line by line

I have the following problem: I need to input a file with 12 lines. Each line consist of 8 characters. I have to output it in a file with 8 lines and 12 characters. I have to read the input line by line and output each line at the same time. So I'm not allowed to read my input first and after i read it just cut in in 8 lines with 12 characters. I'm using BufferedReader to read my file and BufferedWriter to write to my file. So by example:
Input:
12345678
qwertyui
asdfghjk
Output:
12345678qwer
tyuiasdfghjk
Edit: It's an homework assignment indeed.
BufferedWriter bufferedWriter = null;
FileReader fr;
try {
fr = new FileReader(new File(directory to file));
bufferedWriter = new BufferedWriter(new FileWriter(directory to file);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
bufferedWriter.write(output);
bufferedWriter.newLine();
line = br.readLine();
}
br.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
This is how i read my inputfile and write to an outputfile, and it's the code I have at the moment.
Use the read method of Reader class. (FileReader is a descendant of Reader).
I'm not going to implement the whole logic but here is a skeleton to work on.
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream =
new FileReader("inputfile.txt");
outputStream =
new FileWriter("outputfile.txt");
int c;
int counter = 1;
while ((c = inputStream.read()) != -1) {
//keep a counter that will cycle for 12 characters
//check if c represents a alphabet or number, write it to file else skip
//when counter is 12 write a newline
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
The read method allows you to control how many characters to read:
See BufferedReader#read.
Same with write

How can you pick one line from a text file and transform it into an array object?

Okay this is code and I need to somehow take a line from the textfile and transform into an array object. like p[0] = "asdasdasd"
public class Patient2 {
public static void main(String args[])
{
int field = 0;
String repeat = "n";
String repeat1 = "y";
Scanner keyIn = new Scanner(System.in);
// FILE I/O
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Patient.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
ArrayList<Patient1> patients=new ArrayList<Patient1>();
Patient1 p =new Patient1();
//set value to the patient object
patients.add(p);
System.out.println(p);
}
}
Instead of printing it to console you can add it to List<String>
List<String> lines = new ArrayList<String>();
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
lines.add(strLine)
}
Note: your code can be much cleaner, you can handle closing resources in finally
Just use an ArrayList<String> with add(strline); and use toArray(new String []) to get the array after input stream has been closed.
ArrayList<String> list = new ArrayList<String>();
...
while ((strLine = br.readLine()) != null) {
list.add(strLine);
}
...
String [] s = list.toArray(new String []);

How to open a txt file and read numbers in Java

How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.

Read data from a text file using Java

I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
You should not use available(). It gives no guarantees what so ever. From the API docs of available():
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
You would probably want to use something like
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null)
process(str);
in.close();
} catch (IOException e) {
}
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)
How about using Scanner? I think using Scanner is easier
private static void readFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Read more about Java IO here
If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
// Do something with line
}
(Note that this code doesn't handle exceptions or close the stream, etc)
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
// Uncomment the line below if you want to skip the fist line (e.g if headers)
// line = br.readLine();
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
} catch (IOException e) {
System.out.println("ERROR: unable to read file " + file);
e.printStackTrace();
}
You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method:
FileUtils.readFileToString("yourFileName");
Hope it helps you..
The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0
In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:
private List<String> loadFile() {
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
List<String> list = null;
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
//The way that I read integer numbers from a file is...
import java.util.*;
import java.io.*;
public class Practice
{
public static void main(String [] args) throws IOException
{
Scanner input = new Scanner(new File("cards.txt"));
int times = input.nextInt();
for(int i = 0; i < times; i++)
{
int numbersFromFile = input.nextInt();
System.out.println(numbersFromFile);
}
}
}
Try this just a little search in Google
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try using java.io.BufferedReader like this.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
Yes, buffering should be used for better performance.
Use BufferedReader OR byte[] to store your temp data.
thanks.
user scanner it should work
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
public class ReadFileUsingFileInputStream {
/**
* #param args
*/
static int ch;
public static void main(String[] args) {
File file = new File("C://text.txt");
StringBuffer stringBuffer = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
while((ch = fileInputStream.read())!= -1){
stringBuffer.append((char)ch);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File contents :");
System.out.println(stringBuffer);
}
}
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}

Categories