Where do I insert my file location into this code? - java

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

Related

reading text from a relative file path

I have an absolute file path in my java program that contains some text. This is the code:
import java.io.*;
import java.util.*;
public class RoughCode {
public static void main(String[] args) {
try {
File rules=new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1\\GameShowRules.txt");
Scanner scan=new Scanner(rules);// scans the file 'rules'
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());// outputs 'rules' to console
}
}
catch(Exception e) {
System.out.println("File not found");
System.exit(0);
}
}
}
Here, the code works just fine. The output I get is whatever is stored in the file, which is:
The rules of the game are:
You must answer 15 multiple-choice questions correctly in a row to win the jackpot.
You may quit at any time and keep the earnings.
However, what I need is a relative file path so that it runs on any laptop.
In an attempt to do that, I did:
import java.io.*;
import java.net.URI;
import java.util.*;
public class RoughCode {
public static void main(String[] args) {
try {
// Two absolute paths
File absolutePath1 = new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1\\GameShowRules.txt");
File absolutePath2 = new File("C:\\Users\\Owner\\Documents\\ICS4U\\Assignment 1");
// convert the absolute path to URI
URI path1 = absolutePath1.toURI();
URI path2 = absolutePath2.toURI();
// create a relative path from the two paths
URI relativePath = path2.relativize(path1);
// convert the URI to string
String path = relativePath.getPath();
Scanner scan=new Scanner(path);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
catch(Exception e) {
System.out.println("File not found");
System.exit(0);
}
}
}
This does not display the text I need. it just displays "GameshowRules.txt".
How do I get it to output the text stored in the file?
Thanks
Try to use BufferedReader and FileReader. My "data.txt" file is in the same folder as the java program, and works just fine.
I guess you know where will be file of your own program, so you can paste relative path to it.
It looks like this
public class Project {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String data;
while ((data = reader.readLine()) != null) {
System.out.println(data);
}
}
}

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.

Comparing Phrases to whole text

I have two text files. The first user inputs a paragraph of text. The second is a dictionary of terms gotten from an owl file. Like so:
Inferior salivatory nucleus
Retrosplenial area
lateral agranular part
I have coded the bits to make these files. I am stuck as to compare the files so that any whole phrases that appear in the dictionary and the paragraph of text are printed out in the command line in Java.
Try following code, it will help you. Correct your file path in fileName and enter your search condition into the while loop:
public class JavaReadFile {
public static void main(String[] args) throws IOException {
String fileName = "filePath.txt";
//read using BufferedReader, to read line by line
readUsingBufferedReader(fileName);
}
private static void readUsingBufferedReader(String fileName) throws IOException {
File file = new File(fileName);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
//process the line
System.out.println(line);
}
//close resources
br.close();
fr.close();
}
}
You could write the file to a string and iterate over the keys in your dictionary and check if they are present in the paragraph with contains. This probably isn't a particularly efficient solution, but it should work.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
public class Test {
public static void main(String[] args) throws IOException {
String fileString = new String(Files.readAllBytes(Paths.get("dictionary.txt")),StandardCharsets.UTF_8);
Set<String> set = new HashSet<String>();
set.add("ZYMURGIES");
for (String term : set) {
if(fileString.contains(term)) {
System.out.println(term);
}
}
}
}
Here's a Java 8 version of the contains checking.
package insert.name.here;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class InsertNameHere {
public static void main(String[] args) throws IOException {
String paragraph = new String(Files.readAllBytes(Paths.get("<paragraph file path>")));
Files.lines(Paths.get("<dictionary file path>"))
.filter(paragraph::contains)
.forEach(phrase -> System.out.printf("Paragraph contains %s", phrase));
}
}

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