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();
}
}
Related
I don't know how to read the last line from the file so it will also be saved in waterlevel.
I have to make in addition to the code a strukogram.
import java.util.Scanner;
import java.io.FileWriter;
import java.ioException;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Dam{
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
FileWriter fw;
FileReader fr;
int waterLevel;
String text;
do {
System.out.println("give the current water level");
try {
fw = new FileWriter("waterLevel.txt");
text = sc.nextInt()+ "\n";
fw.write(text,0,text.length());
fw.flush();
fw.close;
} catch (IOException e) {
e.printStackTrace();
}
} while (waterLevel < 15);
System.out.println("warning");
}
}
I ready set the resources folder in it. But the code still not working. But use full file path name works everytime.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Main main = new Main();
//main.readFile("C:\\Users\\JIAN HE\\IdeaProjects\\DragDrop\\src\\resources\\text.txt");
main.readFile("text.txt");
//MyFrame myFrame = new MyFrame();
//System.out.println(Main.class.getResource("/resources/elephant.png"));
}
public void readFile(String fileName) throws FileNotFoundException {
File file = new File(getClass().getResource(fileName).getPath());
//File file = new File("C:\\Users\\JIAN HE\\IdeaProjects\\DragDrop\\src\\resources\\text.txt");
//File file = new File("C:\\Users\\JIAN HE\\IdeaProjects\\DragDrop\\src\\resources\\text.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
}
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 .
The following code behaves as expected if I run this from the actual command line (i.e. javac ..., java XXX.java (args[0]) (args[1]).
However if I try to set the command line args through eclipse I get the "Error with input or output file" error, but if the cmd line args in eclipse lenght != 2 I also get the "Must specify input file...." so I know it is assigning them
Does anyone know what the deal is with this?
public class main {
public static Scanner fileScanner(String fName) throws FileNotFoundException {
return new Scanner(new FileInputStream(fName));
}
public static PrintStream printStream(String fName) throws FileNotFoundException {
return new PrintStream(new FileOutputStream(fName));
}
public static void main(String[] args) {
Scanner scan=null;
PrintStream out=null;
if(args.length != 2) {
System.out.println("Must specify input file & output file on cmd line");
System.exit(0);
}
try {
scan = fileScanner(args[0]);
out = printStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println("Error with input or output file");
System.exit(0);
}
I tried you program, it works fine in eclipse when i give filename with complete path.
package so.ch1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class main {
/**
* #param args
*/
public static Scanner fileScanner(String fName) throws FileNotFoundException {
return new Scanner(new FileInputStream(fName));
}
public static PrintStream printStream(String fName) throws FileNotFoundException {
return new PrintStream(new FileOutputStream(fName));
}
public static void main(String[] args) {
Scanner scan=null;
PrintStream out=null;
if(args.length != 2) {
System.out.println("Must specify input file & output file on cmd line");
System.exit(0);
}
try {
scan = fileScanner(args[0]);
out = printStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println("Error with input or output file");
System.exit(0);
}
}
}
Args given: F:/temp/abc.txt F:/temp/xyz.txt
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.