I am facing some problem while reading the contents of file.
Although program is reading contents, it is skipping odd line data from file.
Example of file:
Czech Republic____06092015_091108
France____06092015_060256
Greece____06092015_073528
Hungary____06092015_093424
India____06092015_120741
Indonesia____06092015_140940
Kazakhstan____06092015_095945
Mexico____06092015_061522
Turkey____06092015_100457
But the output is:
java.io.DataInputStream#1909752
France____06092015_060256
Hungary____06092015_093424
Indonesia____06092015_140940
Mexico____06092015_061522
I don't understand why it is giving output as in this format.
I have line separator in input file, can it be causing the problem?
public class tst {
// Main method
public static void main(String args[]) {
// Stream to read file
FileInputStream fin;
int k = 0;
try {
// Open an input stream
fin = new FileInputStream(
"C:/Users/BOT2/Desktop/MC_WIth_DATA_Files.txt");
DataInputStream in1 = new DataInputStream(fin);
// Read a line of text
System.out.println(new DataInputStream(fin));
// Close our input stream
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
while (br1.readLine() != null) {// System.out.println(k);k++;
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
// Catches any error conditions
catch (IOException e) {
System.err.println("Unable to read from file");
System.exit(-1);
}
}
}
You have two errors. First, you print out the dataStream object for some reason. Get rid of :
// Read a line of text
System.out.println( new DataInputStream(fin) );
Next, you throw away lines of text. Try this instead:
String line;
while ((line = br1.readLine()) != null){
System.out.println(line);
}
The first line is printed by:
System.out.println( new DataInputStream(fin) );
it gives you te result of new DataInputStream(fin).toString()
The next lines are printed in this format, bacause you read two lines per loop:
first line while (br1.readLine() != null){ and second line: System.out.println(br1.readLine()); }
So you have to change your code to:
String line;
while ((line =br1.readLine()) != null){//System.out.println(k);k++;
System.out.println(line );
}
br1.close();
fin.close();
The problem is here
while (br1.readLine() != null){
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
When you call br1.readLine() it reads out the current line and move the cursor position to point to the next line. You are calling this method twice causing you to skip alternative lines. You should call readLine() only once per iteration.
i suggest cleaner code so you and whoever reads it will understand immediately what you are doing.
Try this :
Scanner read;
try{
read=new Scanner(new FileReader("your path"));
while(read.hasNext()){
System.out.println(read.nextLine);
}
read.close();
}
catch(FileNotFoundException e){
}
Related
So I'm having a few troubles here. I need to be able to write my output to a file, and have it contain only the keywords specified in the code. This code is writing nothing to the file, and it only opens another box for user input. How do I get it to close the input box after the user inputs the file name, get it to write the output to the file, and get the output to display in the compiler? Thanks!
import java.util.*;
import java.io.*;
public class Classname {
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException,
FileNotFoundException {
String filename;
// Connecting to a file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the text file to a file object
File log = new File( filename);
String textLine = null; // Null
String outLine = ""; // Null
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
try
{
// assigns the file to a filereader object..this will throw an error if
the file does not exist or cannot be found
BufferedReader infile = new BufferedReader(new FileReader(log));
try
{
// read data from a file..this will throw and error if something goes
wrong reading (empty or past end of file)
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.printf("%s\n",outLine);
}// end of while
} // end of try
finally // finally blocks get executed even if an exception is thrown
{
infile.close();
outFile.close();
}
}// end of try
catch (FileNotFoundException nf) // this goes with the first try because it
will throw a FileNotFound exception
{
System.out.println("The file \""+log+"\" was not found");
}
catch (IOException ioex) // this goes with the second try because it will
throw an IOexception
{
System.out.println("Error reading the file");
}
} /// end of main
} // end of class
What you need is to end the while(sc.hasNext()) while loop because the Scanner sc will always have a next because you are literally saying asking yourself if you got the line from the user then wait for next line with sc.nextLine(); then you are putting it into a string so next time you ask yourself do i have the line the answer is yes,anyways it's a little complicated to get over this issue you need to change the while loop to have a special word that will brake it,so you have to change it from:
while(sc.hasNext()){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
}
To,for example:
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
}
Also you need to check if the file entered by the user exists and actually add the text from the console to the file,so it would look something like this:
if(!log.exists())log.createNewFile();
// Connecting to a file with a buffer
PrintWriter logFile = new PrintWriter(
new BufferedWriter(
new FileWriter(log.getAbsolutePath())));
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
logFile.println(line);
}
logFile.close();
Now all we have to do is print the output to the console when writing it to the logFile,so the while((textLine = infile.readLine()) != null),will now look a little something like this:
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.println(outLine);
System.out.println(outLine);
}// end of while
} // end of try
So in the end the hole thing should look a little something like this:
import java.util.*;
import java.io.*;
public class Classname{
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws IOException,
FileNotFoundException {
String filename;
// Connecting to a file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the text file to a file object
File log = new File(filename);
String textLine = null; // Null
String outLine = ""; // Null
if(!log.exists())log.createNewFile();
// Connecting to a file with a buffer
PrintWriter logFile = new PrintWriter(
new BufferedWriter(
new FileWriter(log.getAbsolutePath())));
while(true){
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
if(line.contains("END"))
break;
logFile.println(line);
}
logFile.close();
try{
// assigns the file to a filereader object..this will throw an error if the file does not exist or cannot be found
BufferedReader infile = new BufferedReader(new FileReader(log));
try
{
// read data from a file..this will throw and error if something goes wrong reading (empty or past end of file)
while((textLine = infile.readLine()) != null)
{
//System.out.printf("%s\n",textLine);
outLine = textLine.toUpperCase();
outFile.println(outLine);
System.out.println(outLine);
}// end of while
} // end of try
finally // finally blocks get executed even if an exception is thrown
{
infile.close();
outFile.close();
}
}// end of try
catch (FileNotFoundException nf) // this goes with the first try because it will throw a FileNotFound exception
{
System.out.println("The file \""+log+"\" was not found");
}
catch (IOException ioex) // this goes with the second try because it will throw an IOexception
{
System.out.println("Error reading the file");
}
} /// end of main
} // end of class
If this is not what you are looking for i'm sorry,but i tried to make it do want you described you wanted,i mean it does write the output to the file, and get the output to display in the compiler,here's what the compiler console looks like:
Please enter full name of the file: test.txt
hi
hi
hi
END
HI
HI
HI
I'm sorry if this is not what you wanted but i tried my best,hope it helps.
I am writing a file IO method and have a while loop within a try/catch clause. Thus works though my txt file that I am reading must have a new blank line at the end in order for it to work corrctly. If the txt file does not have this blank line then it runs but also produces my catch exception error msg at the end.
Any ideas on how to implement a NoSuchElementException to fix this.
Thanks
Change the whileloop to:
while((line = reader.readLine()) != null){
Sysout...
}
And it will work.
Problem with your code is, that you read a line and than enter the whileloop again.
Scanner in = new Scanner(filename);
File fileName = new File(filename);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
System.out.println("ERROR FILE NOT FOUND");
in.close(); // close scanner if file not found
}
replace
String line = reader.readLine();
while(line.length() > 0) {
System.out.println(line);
line = reader.readLine();
}
with
String s;
while((s = reader.readLine()) != null) {
System.out.println(s);
}
So I have this method here that should return the amount of lines in a csv file. Pretty simple right? Thing is instead of returning the amount of lines in the csv file(in this case 15) it returns 66. I honestly have know Idea why this would happen. I checked the csv file and verified that it is indeed 15 lines long with no empty lines. Also does anyone know why my Jpanes wont display without those three lines commented lines, my ide says the variables aren't in use anywhere.
public static int getLineCount(){
int line=0;
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data =inputStream.next();//this line is useless but the program doesn't display with out it
String[] values = data.split(",");//this line is useless but the program doesn't display with out it
i++;//this line is useless but the program doesn't display with out it
line++;
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
return line;
}
Use BufferedReader instead of Scanner:
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
while(reader.readLine() != null){
line++;
}
public static int getLineCount(){
String csvFilePath = "C:\\Users\\uzochi\\desktop\\txt.csv";
String line = "";
int numberOfLines=0;
try {
BufferedReader br = new BufferedReader(new FileReader(csvFilePath));
while (( line = br.readLine()) != null) {
numberOfLines++;
}
}catch(FileNotFoundException e){
//
}catch (IOException ex) {
//
}
return numberOfLines;
}
So I'm having an issue reading a text file into my program. Here is the code:
try {
InputStream fis = new FileInputStream(targetsFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//while(br.readLine()!=null){
for (int i = 0; i < 100; i++) {
String[] words = br.readLine().split(" ");
int targetX = Integer.parseInt(words[0]);
int targetY = Integer.parseInt(words[1]);
int targetW = Integer.parseInt(words[2]);
int targetH = Integer.parseInt(words[3]);
int targetHits = Integer.parseInt(words[4]);
Target a = new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
} catch (Exception e) {
System.err.println("Error: Target File Cannot Be Read");
}
The file I am reading from is 100 lines of arguments. If I use a for loop it works perfectly. If I use the while statement (the one commented out above the for loop) it stops at 50. There is a possibility that a user can run the program with a file that has any number of lines, so my current for loop implementation won't work.
Why does the line while(br.readLine()!=null) stop at 50? I checked the text file and there is nothing that would hang it up.
I don't get any errors from the try-catch when I use the while loop so I am stumped. Anyone have any ideas?
also very comprehensive...
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
You're calling br.readLine() a second time inside the loop.
Therefore, you end up reading two lines each time you go around.
You can use a structure like the following:
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
In case if you are still stumbling over this question.
Nowadays things look nicer with Java 8:
try {
Files.lines(Paths.get(targetsFile)).forEach(
s -> {
System.out.println(s);
// do more stuff with s
}
);
} catch (IOException exc) {
exc.printStackTrace();
}
Thank you to SLaks and jpm for their help. It was a pretty simple error that I simply did not see.
As SLaks pointed out, br.readLine() was being called twice each loop which made the program only get half of the values. Here is the fixed code:
try{
InputStream fis=new FileInputStream(targetsFile);
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
String words[]=new String[5];
String line=null;
while((line=br.readLine())!=null){
words=line.split(" ");
int targetX=Integer.parseInt(words[0]);
int targetY=Integer.parseInt(words[1]);
int targetW=Integer.parseInt(words[2]);
int targetH=Integer.parseInt(words[3]);
int targetHits=Integer.parseInt(words[4]);
Target a=new Target(targetX, targetY, targetW, targetH, targetHits);
targets.add(a);
}
br.close();
}
catch(Exception e){
System.err.println("Error: Target File Cannot Be Read");
}
Thanks again! You guys are great!
Concept Solution:br.read() returns particular character's int value so loop
continue's until we won't get -1 as int value and Hence up to there it prints
br.readLine() which returns a line into String form.
//Way 1:
while(br.read()!=-1)
{
//continues loop until we won't get int value as a -1
System.out.println(br.readLine());
}
//Way 2:
while((line=br.readLine())!=null)
{
System.out.println(line);
}
//Way 3:
for(String line=br.readLine();line!=null;line=br.readLine())
{
System.out.println(line);
}
Way 4:
It's an advance way to read file using collection and arrays concept
How we iterate using for each loop.
check it here
http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html
In addition to the answer given by #ramin, if you already have BufferedReader or InputStream, it's possible to iterate through lines like this:
reader.lines().forEach(line -> {
//...
});
or if you need to process it with given order:
reader.lines().forEachOrdered(line -> {
//...
});
I have a bunch of strings that I'm writing to a file:
private void writeScoreToFile(BlastScore result)
{
try{
FileWriter fstream = new FileWriter(getFilesDir() + CaptureActivity.BLAST_SCORES,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(Integer.toString(result.getBlastScore()));
out.close();
}catch (Exception e){
System.err.println("Write Error: " + e.getMessage());
}
}
I would like to read it back in as a List.
private List<String> getArrayFromFile(String filename) throws IOException
{
FileReader fileReader = new FileReader(getFilesDir() + filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines;
}
The list that is being written is:
100
96
100
96
100
When I print the List it looks like
10-28 21:22:31.130: I/System.out(936): Last Score: 1009610096100
Here is the code I am using to print it:
try {
List<String> blastScores = getArrayFromFile(CaptureActivity.BLAST_SCORES);
System.out.println("Last Score: " + blastScores.get(blastScores.size()-1));
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Read Error: " + e.getMessage());
}
I'm trying to get the n-1 element.
I'm not sure what I'm doing wrong.
When you are writing the Integers or Integer Strings you are not putting a new line character after each output. Hence, your file has only one line of data, which line you are getting as a continuous String...
To fix, add a line separator like write.newLine() in between separate write() calls.
The code which writes the scores uses
out.write(Integer.toString(result.getBlastScore()));
This means that if the method is called with scores 12, 100 and 2, your file will look like
121002
since you don't write any separator. How do you want to parse this into three numbers correctly?
Use a PrintWriter that wraps the BufferedWriter, and use its println method to write the score.
Note that writing the scores one by one by opening the file and closing it each time won't be very fast. BTW, using a BufferedWriter just to write a single integer won't gain any benefit. You also have bad exception handling : the streams and readers/writers should always be closed in a finally block.
In your writeScoreToFile function I don't see any new line or any sort of delimiter that would separate each score being written.
In that case your file would in fact contain 1009610096100 on a single line and the loop inside getArrayFromFile would only be executed once:
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
Therefore your List<String> only contains 1 element and the code blastScores.get(blastScores.size()-1) will get the last and only element, that obviously being 1009610096100.