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);
}
}
}
Related
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");
For some reason, although I have already downloaded the CSV files, my program is unable to read them. My code is below, and it checks if the CSV file exists. If it does not, it goes to the URL and downloads and reads the code. However, it always re-downloads the code although it is in the path folder.
private void loadData(String path, String url) throws IOException{
File f = new File(path);
System.out.println("looking for path " + path);
if(f.exists()) {
readSavedFile(path); //method to load data
}
else{
System.out.println("Need to download from internet");
downloadAndRead(url, path);
}
}
This code outputs
looking for path C:\Users\n_000\workspace\Program\GOOG.csv
Need to download from internet.
looking for path C:\Users\n_000\workspace\Program\CHK.csv
Need to download from internet.
The code that I'm using to create the path is this:
String save = "filename"; //in program use this is the name of the stock eg GOOG or CHK
Path currentRelativePath = Paths.get("");
String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\";
path = savedFolder+save+".csv";
Its working fine,i didn't see any issues,i am posting my tested code,hope it may be useful.
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String ar[])
{
Test test=new Test();
}
public Test()
{
String save = "GOOG"; //in program use this is the name of the stock eg GOOG or CHK
Path currentRelativePath = Paths.get("");
String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\";
String path = savedFolder+save+".csv";
String url=null;
try
{
loadData(path,url);
} catch (IOException e)
{
e.printStackTrace();
}
}
private void loadData(String path, String url) throws IOException
{
File f = new File(path);
System.out.println("looking for path " + path);
if(f.exists()) {
readSavedFile(path); //method to load data
}
else{
System.out.println("Need to download from internet");
downloadAndRead(url, path);
}
}
public void readSavedFile(String path)
{
System.out.println("Reading file");
}
public void downloadAndRead(String url,String path)
{
System.out.println("Downloding file");
}
}
How can i load a text file with a runnable .jar file, It works fine when it's not jarred but after i jar the application it can't locate the file. Here's what i'm using to load the text file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class PriceManager {
private static Map<Integer, Double> itemPrices = new HashMap<Integer, Double>();
public static void init() throws IOException {
final BufferedReader file = new BufferedReader(new FileReader("prices.txt"));
try {
while (true) {
final String line = file.readLine();
if (line == null) {
break;
}
if (line.startsWith("//")) {
continue;
}
final String[] valuesArray = line.split(" - ");
itemPrices.put(Integer.valueOf(valuesArray[0]), Double.valueOf(valuesArray[1]));
}
System.out.println("Successfully loaded "+itemPrices.size()+" item prices.");
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (file != null) {
file.close();
}
}
}
public static double getPrice(final int itemId) {
try {
return itemPrices.get(itemId);
} catch (final Exception e) {
return 1;
}
}
}
Thanks for any and all help.
There are two reasons for this. Either the file is now embedded within the Jar or it's not...
Assuming that the file is not stored within the Jar, you can use something like...
try (BufferedReader br = new BufferedReader(new InputStreamReader(PriceManager.class.getResourceAsStream("/prices.txt")))) {...
If the prices.txt file is buried with the package structure, you will need to provide that path from the top/default package to where the file is stored.
If the file is external to the class/jar file, then you need to make sure it resides within the same directory that you are executing the jar from.
if this is your package structure:
Correct way of retrieving resources inside runnable or.jar file is by using getResourceAsStream.
InputStream resourceStream = TestResource.class.getResourceAsStream("/resources/PUT_Request_ER.xml");
If you do getResource("/resources/PUT_Request_ER.xml"), you get FileNotFoundException as this resource is inside compressed file and absolute file path doesn't help here.
I'm using Windows7. I've written this simple java code:
package filetest;
import java.io.File;
public class FileTest {
public static void main(String[] args) {
File myfile = new File("C://test//test.txt");
if (myfile.exists()) {
System.out.println("file exists");
} else {
System.out.println("file doesn't exist");
}
}
}
The file DOES exists in C:/test/test.txt, but the answer is that file doesn't exists.
Why?
EDITED:
I've changed the code and it still doesn't find the file, but now it creates the file. So I can write to that directory. And the created file is named "test"
package filetest;
import java.io.File;
import java.util.*;
public class FileTest {
public static void main(String[] args) {
File myfile = new File("C:\\test\\test.txt");
final Formatter newfile;
if (myfile.exists()) {
System.out.println("file exists");
} else {
System.out.println("file doesn't exist");
try {
newfile = new Formatter("C://test//test.txt");
System.out.println("file has been created");
} catch(Exception e) {
System.out.println("Error: " + e);
}
}
}
}
In windows path separator used is '\' for these you need to escape backslash.So your code will be something like:
public class FileTest {
public static void main(String[] args) {
File myfile = new File("C:\\test\\test.txt");
if (myfile.exists()) {
System.out.println("file exists");
} else {
System.out.println("file doesn't exist");
}
}
}
You don't need to double your slashes. You have to user wether "/" or "\\".
EDIT :
The weird thing is that I tried it out and both "/" and "\\" work fine for me. In fact, it works regardless of the number of "/" I use... for example "C:////test/////////test.txt" is okay. You have another problem, and I have no idea of what it could be.
I would recommend using isFile() instead of exists(). Its a better way of checking if the path points to a file rather than if a file exists or not. exists() may return true if your path points to a directory.
#SSorensen In your EDITED code, you added the backslash properly
# line 7
File myfile = new File("C:\\test\\test.txt");
but you forgot to update slashes with backslashes # line 14
newfile = new Formatter("C://test//test.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.