Connecting Tech Pros Worldwide Forums | Help | Site Map

How to read from textfile in Java

Member
 
Join Date: Dec 2007
Posts: 35
#1: Dec 12 '07
Hi i'm a student studying java (i'm still a beginner). i have a project were i have to do a quiz with a set of questions. So i think that i have to type the questions in a textfile for example in notepad. But i need to call it from java. My problem is that i need to read each question as a whole sentence. The way it is written it is broken, writing a word on each line. How can i read it as a whole sentence? This is the source code i have written:


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

class FileInputScannerDemo2
{
public static void main( String[] args ) throws FileNotFoundException
{
// declare and initialize variables

String question = "";


Scanner LineInput = null;
// input
File inFile = new File( "questions.txt" ); // locate data source

// processing
if( inFile.exists() )
{
// create Scanner object with file object as source
LineInput = new Scanner( inFile );

while (LineInput.hasNext() )
{

question = LineInput.next();
this.getClass().getResourceAsStream("questions.txt ");

System.out.println( question+" ");
}
}
else
{
System.out.println( inFile + " does not exist" );
System.exit(0);
}


} // end main

} // end class

Pls if you can help me
Thanks a lot.

BigDaddyLH's Avatar
Moderator
 
Join Date: Dec 2007
Location: Kelowna, BC Canada
Posts: 1,212
#2: Dec 12 '07

re: How to read from textfile in Java


The simplest way to break a stream of characters into lines is to use BufferedReader and its readLine method. I suppose you could stick with Scanner, but it doesn't make it any easier.
Reply