FileNotFoundException on .dat file - java

Propably it's simple error but I'm stuck. I keep a .dat file with a text I want to read in the program in the same package as main and base class, and I've got a FileNotFoundException. I tried to change the file on .txt, getting the URI syntax, but that didn't help. Where's the point?
The main class:
package syseks;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
public class main {
public static syseks.base ba;
public main(syseks.base ba){
ba = this.ba;
}
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
ba = new base();
String[] py = ba.loadData('p');
System.out.print(py);
}
}
And the loadData method from base class:
public String[] loadData(char param) throws FileNotFoundException{
List<String> strlist = new ArrayList<String>();
if(param == 'p'){
Scanner sc = new Scanner(new File("py.dat")); //HERE'S THE CRASH
while(sc.hasNextLine()){
strlist.add(sc.nextLine());
}
}
else{
Scanner sc = new Scanner(new File("wy.dat"));
while(sc.hasNextLine()){
strlist.add(sc.nextLine());
}
}
String[] da = strlist.toArray(new String[0]);
return da;
}

Supply an absolute path to the File constructor argument. Something like:
Scanner sc = new Scanner(new File("/home/foo/proj/myapp/src/syseks/py.dat"));

Display the current directory using System.getProperty("user.dir"). Make sure it's the directory in which you've saved the .dat file.

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");

Already set the resources folder. But getclass().get resource().getPath() still failed in Intellj IDEA Java

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());
}
}
}

Reset the file pointer back to starting position

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 .

Search and update a string in a text file in JAVA

I have two text files namely - item.txt (file 1) and temp.txt (file 2). My goal is to search for a name in the file 1 and if found then replace it with a different name and write the updated line to file 2. Also, I have a method that checks for the lines for the string I searched in file 1. The lines that do not contain that string will be added to file 2.
So, here is where I'm stuck. Everything works fine except the part where I want to delete file 1 and rename file 2 by file 1 (i.e item.txt). Can someone please help me with any correction? I am still a beginner in Java, so my code might not be the best looking code as one might expect but this is what I tried so far. Thanks
The problem is when i compile the code the updated data is written to file2 and file1 which was supposed to get deleted doesn't delete. So, what could be the problem?
package project4;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class kitkat {
PrintWriter out,in;
Scanner in;
Scanner temp;
File file1 = new File("item.txt");
File file2 = new File("temp.txt");
public void write() throws FileNotFoundException {
out = new PrintWriter(file1);
out.println("User1"+ "\t"+"639755"+"\t"+"400");
out.println("User2"+ "\t"+"639725"+"\t"+"800");
out.close();
}
public void nfile() throws IOException {
n = new PrintWriter(new FileWriter(file2,true));
}
Scanner input = new Scanner(System.in);
String replacement = "User3";
String search;
String total;
public void search() {
System.out.println("Enter your search name");
search = input.nextLine();
total = search;
}
public void lolipop() throws IOException {
in = new Scanner(file1);
search();
while(in.hasNext()) {
String a,b,c;
a = in.next();
b = in.next();
c = in.next();
if(a.contains(search)) {
System.out.println("Your match is found"+search);
a = replacement;
System.out.println(a+b+c);
n.file();
n.println(a+"\t"+b+"\t"+c);
n.close();
}
}
}
public void jellybeans() throws IOException {
temp = new Scanner(file1);
while(temp.hasNext()) {
String p,q,r;
p = temp.next();
q = temp.next();
r = temp.next();
if(!(p.contains(total))) {
System.out.println(p+q+r);
n.file();
n.println(p+"\t"+q+"\t"+r);
n.close();
renamefile();
}
}
}
public void renamefile() {
file1.delete();
file2.renameTo(file1);
}
}
package project4;
import java.io.FileNotFoundException;
import java.io.IOException;
public class tuna {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
kitkat kt = new kitkat();
kt.lolipop();
kt.jellybeans();
}
}
Change this:
public void renamefile() {
String file1Path = file1.getAbsolutePath();
file1.delete();
file2.renameTo(new File(file1Path));
}
According to the Javadoc of File.renameTo(…) the behavior of this method is platform dependent. If the rename does not succeed it simply returns false without throwing an exception. So I guess this would be the case here.
You can try the newer (since Java 7) Files.move(…). This method is platform independent and has propper error handling, throwing exceptions with a problem description.

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