Reset the file pointer back to starting position - java

Is there any way I can reuse the Scanner object to read the same file again.
There is RandomAccessFile class that provides random access (seek) but I am looking for some code that uses Scanner. I know how to go to the stating position of the file by creating a new Scanner object, but the code looks messy.
Is there a neat and short method to do the same.
Thanks in advance:-)
Also could you suggest good source/tutorial for learning file handling :p
Here is what I am trying to do:
Container.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;
public class Container {
private Scanner sc;
private Formatter f;
void openFile() throws FileNotFoundException{
sc=new Scanner(new File("source"));
}
void readData(){
while(sc.hasNext()){
System.out.println(sc.next());
}
}
void readlineData(){
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
void closeFile(){
sc.close();
}
void addData() throws FileNotFoundException{
f=new Formatter("source");
f.format("%s%s", "hi "," hello");
}
}
Client.java
import java.io.FileNotFoundException;
public class Client {
public static void main(String[] args) throws FileNotFoundException {
Container c=new Container();
try {
c.openFile();
} catch (FileNotFoundException e) {
System.out.println("No file with this name");
}
//reading word by word
c.readData();//there is content already in the file
//reading line by line
c.readlineData();
//changing the content of the file
c.addData();
//reading the file again
c.readData();
//closing the file
c.closeFile();
}
}
Here i have made a client and a container class.
In the container class i have methods to create a file,read file word by word ,read line by liine and close file.
In the client class i have called these methods .

Related

Where do I insert my file location into this code?

I have this code that reads a file and returns the content as String but I don not know where to put the file path or location
C:\Users\johnm\eclipse-workspace\W4A6\src\input.in
Any help would be great.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Encryption {
public static String readFile(String filename) throws IOException {
Scanner scanner = new Scanner(new File(filename));
String content = "";
while (scanner.hasNextLine()) {
content += scanner.nextLine();
}
return content;
}
}
Q: Where do I put the file path or location?
A: Whoever calls the readFile() method of your Encryption class will determine the file path name.
One common technique is a "static main", and pass the filepath as a command line parameter.
EXAMPLE:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Encryption {
public static String readFile(String filename) throws IOException {
Scanner scanner = new Scanner(new File(filename));
String content = "";
while (scanner.hasNextLine()) {
content += scanner.nextLine();
}
return content;
}
public static void main (String[] args) {
if (args.length != 1) {
System.out.println("Please enter a filepath");
} else {
Encryption.readFile(args[0]);
}
}
}
Alternatively, you might invoke Encryption.readFile() from a GUI. Or from a web service.
Regardless: the caller should always "know" the filepath, and pass it as an argument to readFile().
So far, you have only defined a method that reads a file with a given filename.
You need to call it using the file path you wish, so in your case:
String content = Encryption.readFile("C:\\Users\\johnm\\eclipse-workspace\\W4A6\\src\\input.in");

How to use Apache Commons IO with Java

I have a question about Apache Commons IO with Java.
The excercice is to read a text file without using Commons IO, and then using it.
For the first one, my code is this, and this works:
import java.util.Scanner;
public class ReadBook {
private Scanner line;
public void openFile(){
try{
line= new Scanner(new File("books.txt"));
}
catch(Exception e){
System.out.println("File not found");
}
}
public void readFile() {
while (line.hasNext()) {
String book = line.next();
System.out.println(book);
}
}
public void closeFile(){
line.close();
}
}
and the main class:
public class mainClass {
public static void main(String[] args){
ReadBook book = new ReadBook();
book.openFile();
book.readFile();
book.closeFile();
}
}
The teacher gave us this class, and now we are supposed to do the same thing with the Apache Commons IO library.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class Utf8File {
public static String loadFileIntoString(String filePath) throws FileNotFoundException, IOException {
return IOUtils.toString(new FileInputStream(filePath), "UTF-8");
}
public static void saveStringIntoFile(String filePath, String content) throws IOException {
File f = new File(filePath);
FileUtils.writeStringToFile(f, content, "UTF-8");
}
}
I was wondering, do you know how to do it?
Last time I programmed with Java was one year ago hahaha so it is a little bit far away in my memory :O
This is the first homework to do (today was the first class).
I hope someone can help me :)
Thanks!

Unable to Read Text File in Java using FileReader and BufferedReader, possible reasons?

Here From the start() method i called the loadMap(filename) method with a text file.But i don't know why though the loadMap() is called but the FileReader and BufferedReader doesn't working. and the text commented below this two File reader's Statement
System.out.print("INside loadMap()"); doesn't printing in the console and the text File isn't reading. What's the problem here occur actually? Help someone please.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DemoClass {
public static void main(String[] args) {
start();
}
public static void start() {
try {
System.out.print("Pobon File Inside");
loadMap("data\\map1.txt");
} catch (Exception e) {
// TODO: handle exception
}
}
private static void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
FileReader fReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fReader);
System.out.print("INside loadMap()");
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
break;
}
if (!line.startsWith("!")) {
lines.add(line);
}
}
System.out.print("INside loadMap()");
}
}
If System.out.print("INside loadMap()") is never called, then an IOException must be thrown when creating the FileReader.
In other words, the file you entered as the parameter when calling loadMap() (data\map1.txt) doesn't exist. You should consider retrieving the file in a different manner, such as placing it in a source folder and then calling getClass().getResource()

Why won't this code read the file?

I'm trying to create a program that reads from a file named Clients and then through a for loop writes to the console. Here's the code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import static java.lang.System.out;
class ShowOccupancy{
public static void main(String args[])
throws FileNotFoundException{
Scanner diskScanner =
new Scanner (new File("Clients"));
out.print("Room Number");
out.print("/t");
out.println("Guests");
for (int roomNum=0; roomNum<10; roomNum++)
{
out.print(roomNum);
out.print("/t");
out.print(diskScanner.nextInt());
}
diskScanner.close();
}
}
Here are the errors in the console:
Exception in thread "main" java.io.FileNotFoundException: Clients (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at ShowOccupancy.main(ShowOccupancy.java:11)
And I created a Clients file for the java project.
This is a sample of how to read text files, hope it helps.
public static void main(String[] args) {
try {
Scanner reader = new Scanner(new File("FILE-PATH-HERE/clients.txt"));
//Prints lines
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
//Prints tokens
/*
while (reader.hasNext()) {
System.out.println(reader.next());
}
*/
reader.close();
} catch (FileNotFoundException ex) {
//Print error
ex.printStackTrace();
}
}

scanner class in java

Hey I'm trying to compile the following piece of code to basically read stuff from a file but it refuses to work. it gives me an java.io.FILENOTFOUNDEXCEPTION error at line4. help would be appreciated.
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
Try putting the absolute path to the file, like
c:\\java\\matrix1.txt or /home/user/java/matrix1.txt
=== OOPS
You need to catch the Exception that's being thrown. Here's a couple options:
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
OR
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) {
File fin = new File ("matrix1.txt");
Scanner sc = null;
try {
scanner = new Scanner(fin);
}
catch(FileNotFoundException e) {
System.out.println("File does not exist...");
return;
}
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
Make sure matrix1.txt is in your src folder if you're using Eclipse.
If you're using an IDE such as Netbeans/Eclipse, you need to put the file to be read in the project folder. This is usually 1 level above the src folder.
A good alternative in case you can't find the folder is to try and create a file. That way, you know where the file was created and you can place the file you want to read in that same folder.

Categories

Resources