import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example 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());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();
Related
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 )
Problem: I can't parse my file test.txt, by spaces. I can 1) read text files, and I can 2) parse strings, but I cannot connect the two and parse a text file! My purpose is to learn how to analyze text files. This is a simplified approach to that.
Progress: Thus far, I can read test.txt using FileReader and BufferedReader, and print it to console. Further, I can parse simple String variables. The individual operations run, but I'm struggling with parsing an actual text file. I believe this is because my test.txt is stored in the buffer, and after I .close() it, I can't print it.
Text File Content:
This is a
text file created, only
for testing purposes.
Code:
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.print(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
// readFileMethod a = new readFileMethod(line);
System.out.println(a.splitIt());
}
}
Preemptive thank you for your sharing your knowledge. Many posts on reading and parsing have been solved here on SO, but I've not the understanding to implement others' solutions. Please excuse me, I've only been learning Java a few months and still struggle with the basics.
Ok lets make the splitting into a mthod
private static void splitIt (String toTest) {
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece.
System.out.println(piece);
}
}
then you can call it from within
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt (line);
}
Building on Scary Wombat and your code, i made some changes.
It should now print the Line that is being read in and each word that is separated by space.
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public static void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.println(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line); // print the current line
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
I am working on a program that evaluates lisp expressions using a stack implemented by either an array or linked list. I need to read the file in from the first line from right to left. Currently I am reading it in from left to right but I do not understand how I can switch it around. Any help you can give me is greatly appreciated! Thank you!
**I know the program is nowhere near complete, I just need to accomplish this before I can continue.
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.*;
import java.io.BufferedReader;
public class A2Q5{
private static Scanner in;
public static void main (String [] args)
{
if(args.length != 2) {
System.out.println("Please execute as: java A2Q5 type infile");
}
BoundedStack<Double> stack;
if(args[0].equals("0"))
stack = new BSArray<Double>(20);
else
stack = new BSLinkedList<Double>();
// The name of the file to open.
String fileName = args[1];
// This will reference one line at a time
//char c = null;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
for (int i = line.length() - 1; i >= 0; i--){
line.charAt(i);
System.out.println(line.charAt(i));
}
}
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file " + fileName);
}
catch(IOException ex) {
System.out.println("Error reading file " + fileName);
}
}
}
Drop the use of FileInputStream and use BufferedReader that you already prepared but never use. Use its method readLine to read info from your file line by line. Once you got an individual line you can iterate through it character by character from the end of the String to its beginning. This is exactly what you want.
So I have a background in c++ and I am trying to learn java. Everything is pretty similar. I am having a problem thought with file i/o. So I am messing around and doing really simple programs to get the basic ideas. Here is my code to read data from a file. So I am reading Core Java Volume 1 by Cay Hortsman and it tells me to write this to read from a file,
Scanner in = new Scanner(Paths.get("myFile.txt");
But when I write it in my code, it gives me a red line under paths. So I am not sure how to read from a file. It does not go into much detail about the subject. So my program below I am trying to just read numbers in from a file and store them in an array.
package practice.with.arrays.and.io;
import java.io.IOException;
import java.nio.file.Path;
import java.util.*;
public class PracticeWithArraysAndIO
{
static final int TEN = 10;
public static void main(String[] args) throws IOException
{
//Declaring a scanner object to read in data
Scanner in = new Scanner(Paths.get("myFile.txt"));
//Declaring an array to store the data from the file
int[] arrayOfInts = new int[TEN];
//Local variable to store data in from the file
int data = 0;
try
{
for(int i = 0; i < TEN; i++)
{
data = in.nextInt();
arrayOfInts[i] = data;
}
}
finally
{
in.close();
}
}
It is not clear why you are doing Paths.get(filename)).
You can wrap a Scanner around a file like this. As the comments below mention, you should choose an appropriate charset for your file.
Scanner in = new Scanner(new File("myFile.txt"), StandardCharsets.UTF_8);
To use the constant above, you need the following import, and Java 7.
import java.nio.charset.StandardCharsets
With my experience in Java, I've used the BufferedReader class for reading a text file instead of the Scanner. I usually reserve the Scanner class for user input in a terminal. Perhaps you could try this method out.
Create a BufferedReader with FileReader like so:
BufferedReader buffReader = new BufferedReader(new FileReader("myFile.txt"));
After setting this up, you can read lines with:
stringName = buffReader.readLine();
This example will set the String, stringName, to the first line in your document. To continue reading more lines, you'll need to create a loop.
You need to import java.nio.file.Paths.
I've used the BufferedReader class.
I hope it is helpful for you
public class PracticeWithArraysAndIO {
static final int TEN = 10;
public static void main(String[] args) throws IOException
{
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("/home/myFile.txt"));//input your file path
int value=0;
int[] arrayOfInts = new int[TEN];
int i=0;
while((value = br.read()) != -1)
{
if(i == 10) //if out of index, break
break;
char c = (char)value; //convert value to char
int number = Character.getNumericValue(c); //convert char to int
arrayOfInts[i] = number; //insert number into array
i++;
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br != null)
br.close(); //buffer close
}
}
}
I wrote a simple program to read the content from text/log file to html with conditional formatting.
Below is my code.
import java.io.*;
import java.util.*;
class TextToHtmlConversion {
public void readFile(String[] args) {
for (String textfile : args) {
try{
//command line parameter
BufferedReader br = new BufferedReader(new FileReader(textfile));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
String outputfile = new String("Test Report"+dateWithoutTime+".html");
FileWriter filestream = new FileWriter(outputfile,true);
BufferedWriter out = new BufferedWriter(filestream);
out.write("<html>");
out.write("<body>");
out.write("<table width='500'>");
out.write("<tr>");
out.write("<td width='50%'>");
if(strLine.startsWith(" CustomerName is ")){
//System.out.println("value of String split Client is :"+strLine.substring(16));
out.write(strLine.substring(16));
}
out.write("</td>");
out.write("<td width='50%'>");
if(strLine.startsWith(" Logged in users are ")){
if(!strLine.substring(21).isEmpty()){
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Red'>");
out.write("</textarea>");
}else{
System.out.println("else if block:");
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Green'>");
out.write("</textarea>");
} //closing else block
//out.write("<br>");
out.write("</td>");
}
out.write("</td>");
out.write("</tr>");
out.write("</table>");
out.write("</body>");
out.write("</html>");
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TextToHtmlConversion myReader = new TextToHtmlConversion();
String fileArray[] = {"D:/JavaTesting/test.log"};
myReader.readFile(fileArray);
}
}
I was thinking to enhance my program and the confusion is of either i should use Maps or properties file to store search string. I was looking out for a approach to avoid using substring method (using index of a line). Any suggestions are truly appreciated.
From top to bottom:
Don't use wildcard imports.
Don't use the default package
restructure your readFile method in more smaller methods
Use the new Java 7 file API to read files
Try to use a try-block with a resource (your file)
I wouldn't write continuously to a file, write it in the end
Don't catch general Exception
Use a final block to close resources (or the try block mentioned before)
And in general: Don't create HTML by appending strings, this is a bad pattern for its own. But well, it seems that what you want to do.
Edit
Oh one more: Your text file contains some data right? If your data represents some entities (or objects) it would be good to create a POJO for this. I think your text file contains users (right?). Then create a class called Users and parse the text file to get a list of all users in it. Something like:
List<User> users = User.parse("your-file.txt");
Afterwards you have a nice user object and all your ugly parsing is in one central point.