I am sorry if this question is already answered on the internet but by looking at the 'similar questions' I couldn't find an answer for my problem.
So basically I'm trying to understand why using PrintWriter to write lines of text into a file apparently skips the first line every 2 lines I give.
This is the method I use in its own class:
public class IO_Utilities {
public static void Write(String outputName){
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(outputName);
} catch (FileNotFoundException e) {
System.out.println(e.toString());
System.exit(0);
}
System.out.println("Write your text:");
Scanner user = new Scanner(System.in);
while(!user.nextLine().equals("stop")) {
String line = user.nextLine();
outputStream.println(line);
}
outputStream.close();
user.close();
System.out.println("File has been written.");
}
When I call it from main with:
IO_Utilities.Write("output.txt");
and write:
first line
second line
third line
stop
stop
The output text is actually:
second line
stop
I am sure the problem is the while loop, because if I input the lines manually one by one it works correctly, but I don't understand exactly why it behaves like it does right now.
while(!user.nextLine().equals("stop")) {
String line = user.nextLine();
outputStream.println(line);
}
You repeat your user.nextLine(); within your loop, so line is not the same as the one you compare to "stop".
Rewrite that part as:
String line = user.nextLine();
while( !line.equals("stop")) {
outputStream.println(line);
line = user.nextLine();
}
Related
I need to try count the number of lines in a file while using "try" and "catch". This is what I have so far. Hoping I could get some help. It just keeps timing out.
public class LineCount {
public static void main(String[] args) {
try {
Scanner in = new Scanner(new FileReader("data.txt"));
int count = 0;
//String line;
//line = in.readLine();
while (in.hasNextLine()) {
count++;
}
System.out.println("Number of lines: " + count);
}catch (Exception e){e.printStackTrace();}
}
}
Seems like you are doing everything but consuming the newline character. To do this with java.util.Scanner, simply run in.nextLine() in your while loop. This Scanner.nextLine() method will return all characters before the next newline and consume the newline character itself.
Another thing to consider with your code is resource management. After opening the Scanner, it should be closed when it'll no longer be read. This can be done with in.close() at the end of your program. Another way to accomplish this is to setup a try-with-resources block. To do this, just move your Scanner declaration like this:
try (Scanner in = new Scanner(new FileReader("data.txt"))) {
Regarding the need for the try-catch block, as part of the Java compilation process, checked-exceptions will be checked if they are caught or thrown from a method. Checked-exceptions are everything that are not RuntimeExceptions or Errors.
It times out because you do not advance the Scanner. If you enter the while loop you will never exit it.
Also it would be better if you use BufferedReader as is is faster than a standard Scanner. Although if the file is small, maybe for readability purposes you do not. But this is up to you. Anyway.
Here you go:
//this is the try-with-resources syntax
//closing the autoclosable resources when try catch is over
try (BufferedReader reader = new BufferedReader(new FileReader("FileName"))){
int count = 0;
while( reader.readLine() != null){
count++;
}
System.out.println("The file has " + count + " lines");
}catch(IOException e){
System.out.println("File was not found");
//or you can print -1;
}
Probably your questiong has already been answered and you should not ask already answered questions before you search, for a while at least.
I am trying to write a piece of code that reads a single line of text from a text file in java using a buffered reader. For example, the code would output the single line from the text file and then you would type what it says and then it would output the next line and so on.
My code so far:
public class JavaApplication6 {
public static String scannedrap;
public static String scannedrapper;
public static void main(String[] args) throws FileNotFoundException, IOException {
File Tunes;
Tunes = new File("E:\\NEA/90sTunes.txt");
System.out.println("Ready? Y/N");
Scanner SnD;
SnD = new Scanner(System.in);
String QnA = SnD.nextLine();
if (QnA.equals("y") || QnA.equals("Y")) {
System.out.println("ok, starting game...\n");
try {
File f = new File("E:\\NEA/90sTunes.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
}
}
}
}
It outputs:
Ready? Y/N
y
ok, starting game...
(and then the whole text file)
But I wish to achieve something like this:
Ready? Y/N
y
ok, starting game...
(first line of file outputted)
please enter (the line outputted)
& then repeat this, going through every line in the text file until it reaches the end of the text file (where it would output something like "game complete")...
This would read the first line ".get(0)".
String line0 = Files.readAllLines(Paths.get("enter_file_name.txt")).get(0);
This block of code reads the whole file line by line, without stopping to ask for user input:
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
Consider adding a statement to the loop body that seeks some input from the user, like you did above when asking if they were ready ( you only need to add one line of code to the loop, like the line that assigns a value to QnA )
I want to have a method that returns the value that is presentend in the while loop. My code represents the reading of a txt file, where I read line by line and my goal is to return everytime it founds a line but is is showing me the same number over and over.
public String getInputsTxtFromConsole() {
String line = "";
//read inputs file
try {
Scanner scanner = new Scanner(inputFile);
//read the file line by line
int lineNum = 0;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
}
} catch (FileNotFoundException e) {
}
return "";
}
As Nick A has said the use of return has, in this context two uses: return the value of a function and exit the function. I you need all the values as the are generated you can, for example,
Call a method that consume the new value:
line = scanner.nextLine();
lineNum++;
//Return statement does not work here
ConsumerMethod(line);
}
Store in a global var like ArrayList, String[],...
Print it System.out.println(line).
...
But you cannot return a value and expect that the function continues working.
As I mentioned, pass the same scanner as a parameter to a method that reads a line and returns the line. You may want to define how it responds once there are no remaining lines.
public String getInputsTxtFromConsole(Scanner scanner) {
try {
if (scanner.hasNextLine()) {
return scanner.nextLine();
}
} catch (FileNotFoundException e) {
}
return null;
}
I would also recommend using a different class to read from a file. BufferedReader would be a better approach.
BufferedReader in = new BufferedReader(new FileReader (file));
... // in your method
return in.readLine(); //return null if the end of the stream has been reached
I am not sure while am receiving a no such element exception. It seems to be an issue with the scanner not reading my file correctly, but I am not sure where I am going wrong.
I am reading a file, then using the scanner to go line by line. But I get unusual behavior, such as missing lines or filenotfound exceptions when I try to do it.
public static void readMylifeLikeABook(String fileName,int maxItems) {
// Read file line by line with different elements on each line
int bookCount=0;
int movieCount = 0;
Book [] bookItem =new Book[maxItems];
Movie [] movieItem =new Movie[maxItems];
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
Scanner line;
while (scanner.hasNext() && ((bookCount+movieCount)<maxItems)) {
line = new Scanner(scanner.nextLine()); // scan next line
if (line.next().contains("Movie")){
movieItem[movieCount]= new Movie();
movieItem[movieCount].setMediaType("Movie");
movieItem[movieCount].setTitle(scanner.nextLine());
movieItem[movieCount].setRef(scanner.nextLine());
movieItem[movieCount].setPrice(Double.valueOf(scanner.nextLine()));
movieItem[movieCount].setDirector(scanner.nextLine());
movieItem[movieCount].setActor(scanner.nextLine());
System.out.println(movieItem[movieCount].getTitle());
movieCount++;
line.close(); // close line
}
else if (scanner.next().contains("Book")){
bookItem[bookCount]= new Book();
bookItem[bookCount].setMediaType("Book");
bookItem[bookCount].setTitle(scanner.nextLine());
bookItem[bookCount].setRef(scanner.nextLine());
bookItem[bookCount].setPrice(Double.valueOf(scanner.nextLine()));
bookItem[bookCount].setAuthor(scanner.nextLine());
System.out.println(bookItem[bookCount].getTitle());
bookCount++;
line.close(); // close line
}
}
scanner.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
//System.out.println(count);
for (int i=0;i<(bookCount+movieCount);i++) {
System.out.println(bookItem[i] +"\n\n "+ movieItem[i]);
}
}
Hmm, is it possible if you can provide the file being read? This can very well be a problem with that File as if the Scanner object does not a following line to be read, it will throw an exception. Make sure the file has the needed amount of lines.
You call line.next() immediately after constructing line. Do you need to do this? If so, perhaps you need to call hasNext() first to ensure there's a token there.
(I'm pretty sure line.next() throws a NoSuchElementException if there's no token.)
Also, check your code against the file format. Are there blank lines in your file?
I have been trying to figure out how to read from a .txt file. I know how to read a whole file, but I am having difficulties reading between two specific points in a file.
I am also trying to use the scanner class and this is what I have so far:
public void readFiles(String fileString)throws FileNotFoundException{
file = new File(fileString);
Scanner scanner = null;
line="";
//access file
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
// if more lines in file, go to next line
while (scanner.hasNext())
{
line = scanner.next();
if (scanner.equals("BGSTART")) //tag in the txt to locate position
{
line = scanner.nextLine();
System.out.println(line);
lb1.append(line); //attaches to a JTextArea.
window2.add(lb1);//adds to JPanel
}
}
.txt file looks something like this:
BGSTART
//content
BGEND
Nothing is posted onto the panel when I run the program.
I am trying to read it between those two points.I don't have a lot of experience in reading from txt file.
Any suggestions?
Thank You.
Assuming that BGSTART and BGEND are on seperate lines, as per #SubOptimal's question, you would need to do this:
boolean tokenFound = false;
while (scanner.hasNextLine())
{
line = scanner.nextLine();
//line, not scanner.
if (line.equals("BGSTART")) //tag in the txt to locate position
{
tokenFound = true;
}
else if (line.equals("BGEND"))
{
tokenFound = false;
}
if(tokenFound)
{
System.out.println(line);
lb1.append(line); //attaches to a JTextArea.
window2.add(lb1);//adds to JPanel
}
}
Some improvements:
try {
Scanner scanner = new Scanner(new FileInputStream(file));
//Moved the rest of the code within the try block.
//As it was before, if there where any problems loading the file, you would have gotten an error message (File not found)
//as per your catch block but you would then have gotten an unhandled null pointer exception when you would have tried to
//execute this bit: scanner.hasNextLine()
boolean tokenFound = false;
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
//line, not scanner.
if (line.equals("BGSTART")) //tag in the txt to locate position
{
tokenFound = true;
} else if (line.equals("BGEND")) {
tokenFound = false;
}
if ((tokenFound) && (!line.equals("BGSTART"))) {
System.out.println(line);
//I am not sure what is happening here.
//lb1.append(line); //attaches to a JTextArea.
//window2.add(lb1);//adds to JPanel
}
}
} catch (Exception e) {
System.out.println("File not found.");
}
File content:
do not show line one
do not show line two
BGSTART
this is a line
this is another line
this is a third line
BGEND
do not show line three
do not show line four
Why don't you use substring? once you have located your BGSTART and BGEND you can capture the string between it somewhere in the lines of the below code:
StringBuilder sb= new StringBuilder();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
sb.append(line);
}
String capturedString = sampleString.substring(sb.toString().indexOf("BGSTART"),
sb.toString().indexOf("BGEND"));
hope this helps
Almost good, but you are doing:
if (scanner.equals("BGSTART")) //tag in the txt to locate position
You should look for file content in line variable not scanner.
So try this:
if (line.equals("BGSTART")) //tag in the txt to locate position