I have a text file in the same package as the class I'm accessing it through, so I don't understand why I'm getting this exception. Where did I go wrong here?
public static boolean someMethod(){
File f = new File("input.txt");
try{
Scanner s = new Scanner(file);
s.useDelimiter(""); //I want to parse by one character at a time
while(s.hasNext()){
...
}
}catch (FileNotFoundException e){
...
}
return false;
}
new File("input.txt") is relative to your current working dir. If you want to access packaged files, you can use getResourceAsStream(String).
Related
I've been trying to read the text file in my java projects, I've been looking for the solution for the whole day, I've tried loads of methods but none of them have worked. Some of them:
(Also, I have to use File and Scanner class)
String file = "fileTest.txt";
var path = Paths.get("test", file);
System.out.println(path);
System.out.println(Files.readString(path));
Exception in thread "main" java.nio.file.NoSuchFileException:
test\fileTest.txt
URL url = ClassLoader.class.getResource("fileTest.txt");
File file = null;
file = new File(url.toURI());
Scanner scanner = new Scanner(file);
scanner.useDelimiter(" ");
while(scanner.hasNext()) {
System.out.println(scanner.toString());
}
Exception in thread "main" java.lang.NullPointerException
File file = new File("../test/fileTest.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter(" ");
while(scanner.hasNext()) {
System.out.println(scanner.toString());
}
scanner.close();
Exception in thread "main" java.io.FileNotFoundException: ..\test\fileTest.txt (The system cannot find the path specified)
The problems here are project structure and how you're trying to locate that file. Conventionally, your java class files should exist within the directory src/main/java and your resource files should exist within src/main/resources. If you follow this convention, you can obtain the resource with a ClassLoader.
try (InputStream input = getClass().getClassLoader().getResourceAsStream("test.txt");
Scanner scanner = new Scanner(Objects.requireNonNull(input)).useDelimiter(" ")) {
while(scanner.hasNext()) {
System.out.println(scanner.toString());
}
} catch (IOException ioe) {
throw new RuntimeException("Something went wrong scanning file!", ioe);
}
All of the answers talking about relative paths are going to work or not work depending on what your working directory is when you are running your program. If you truly want your file to live inside the classpath, what you want to do is use it as a resource and look on how to load resources at runtime. If, on the other hand, you want to treat it just like any other file, you will need to know what the working directory is at runtime if you expect any relative pathing to work, or have the absolute path specified at some known place, like a configuration file.
Reading a file with BufferReader, using try-with-resource which automatically closes the resources when processing has terminated.
See info on Java try-with-resource: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Edit: Ensure you have included the folder as a resource in your build path. How do I add a resources folder to my Java project in Eclipse
String inputFile = "test/fileTest.txt";
List<String> lines = new ArrayList<>();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
Replace
File file = new File("../test/fileTest.txt");
Scanner scanner = new Scanner(file);
with
File file = new File("test/fileTest.txt");
Scanner scanner = new Scanner(file);
Then, if you want to confirm it, just do the following:
System.out.println(file.exists());
Also, replace
while(scanner.hasNext()) {
System.out.println(scanner.toString());
}
with
while(scanner.hasNext()) {
System.out.println(scanner.next());
}
because scanner.toString() can not be used to get an input; it should be scanner.next().
I am simply trying to read a file, my class file exist in the exact same directory as the file I'm trying to read. The file I'm trying to read is called profiles.txt. I have done the exact same method before In extremely similar circumstances and it worked (and still does work), I have no idea why this doesn't. If anyone could explain I would be very grateful.
public static void readProfiles(BST tree) {
try {
BufferedReader getData = new BufferedReader(
new FileReader(
new File("profiles.txt")));
String data = getData.readLine();
while(data != null) {
String[] profileData = data.split(",");
String[] interests = profileData[7].split(";");
tree.insertProfile(new Profile(
profileData[0],
new int[] {Integer.parseInt(profileData[1]), Integer.parseInt(profileData[2]), Integer.parseInt(profileData[3])},
profileData[4],
profileData[5],
profileData[6],
interests
));
data = getData.readLine();
}
getData.close();
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.exit(0);
}
catch(IOException e) {
System.out.println("IO error occured");
System.exit(0);
}
}
The filename is relative and contains no directories, so it needs to be in the current working directory.
Where the class file is has nothing to do it whatsoever.
Try the path relative to the main run file of your program.
I am trying to complete a simple program that uses the command line to replace a specified String in a file. Command line entry would be java ReplaceText textToReplace filename
The code completes, but the file does not replace the specified string. I have Googled similar situations but I cannot figure out why my code is not working.
import java.io.*;
import java.util.*;
public class ReplaceText{
public static void main(String[] args)throws IOException{
if(args.length != 2){
System.out.println("Incorrect format. Use java ClassName textToReplace filename");
System.exit(1);
}
File source = new File(args[1]);
if(!source.exists()){
System.out.println("Source file " + args[1] + " does not exist.");
System.exit(2);
}
File temp = new File("temp.txt");
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(input.hasNext()){
String s1 = input.nextLine();
String s2 = s1.replace(args[0], "a");
output.println(s2);
}
temp.renameTo(source);
source.delete();
}
}
}
Edit: edited the code so I am not reading and writing to the file at the same time, but it still does not work.
First of all you have a problem with your logic. You are renaming your temporary file then immediately deleting it. Delete the old one first, then rename the temporary file.
Another problem is that you are attempting to do perform the delete and rename within your try block:
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
...
temp.renameTo(source);
source.delete();
}
Your streams are not automatically closed until the try block ends. You will not be able to rename or delete while the stream is open. Both delete and renameTo return a boolean to indicate whether they were successful so it may be prudent to check those values.
Correct code may look something like:
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(...)
{
...
}
}
// Try block finished, resources now auto-closed
if (!source.delete())
{
throw new RuntimeException("Couldn't delete file!");
}
if (!temp.renameTo(source))
{
throw new RuntimeException("Couldn't rename file!");
}
You can't replace strings a file in general. You need to read the input line by line, replace each line as necessary, and write each line to a new file. Then delete the old file and rename the new one.
im a newbye and this is my first post. Ive made a game aplication on eclipse that works perfectly. It uses a few .txt files for scores and player options.
The problem is when i try to export it as runnable jar file, well that's the problem, it makes a jar file and makes it impossible for me to write on any of the .txt files i have. I know this because ive tried, well not hundreds but getting close, of solutions and some of which allowed me to read the files but still i cant write on them. I realize this is the normal functioning of a jar file, so my questions are:
How can i have/make an external folder to the jar file in the same directory containing all my txt files? So that it can read and write in those files, and, what methods should i use in my existing code?
Im only showing how i read/write one of those files, but its the same for every other file and im also showing some of the comment on other past solutions:
private final String cubesScore = "resF\\score.txt";
//private final String cubesScore = "/score.txt";
//private final String cubesScore = "//resF//score.txt";
try{
/*
try{
File file = new File(cubesScore);
//FileReader reader = new FileReader(new File(new File("."), "score.txt"));
if(file.createNewFile()){
System.out.println("File created successfully!");
} else{
System.out.println("File already exists.");
}
} catch(IOException e){
System.out.println("An error occurred on score.txt!!");
}
*/
Scanner scanner = new Scanner(new File(cubesScore));
//InputStream source = this.getClass().getResourceAsStream(cubesScore);
//Scanner scanner = new Scanner(source);
/*
InputStream inputStream = this.getClass().getResourceAsStream(cubesScore);
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputReader);
*/
int value;
int i = 0;
while(scanner.hasNext()){
value = scanner.nextInt();
if(value >= 0){
mostCubesDestroyed[i] = value;
System.out.println(value);
}
else
System.out.println("File corrupted");
++i;
}
scanner.close();
} catch (NullPointerException | FileNotFoundException e) {
System.out.println("File Not Found/Null");
}
write:
try {
PrintWriter out = new PrintWriter(cubesScore);
//OutputStream out = this.getClass().getResourceAsStream(cubesScore);
//out = new PrintWriter(out);
//BufferedWriter out = new BufferedWriter(new FileWriter(cubesScore));
//out.write(mostCubesDestroyed[0]);
//out.newLine();
out.println(mostCubesDestroyed[0]);
System.out.println(mostCubesDestroyed[0]+" Cubes GameMode 0");
//out.write(mostCubesDestroyed[1]);
//out.newLine();
out.println(mostCubesDestroyed[1]);
System.out.println(mostCubesDestroyed[1]+" Cubes GameMode 1");
//out.write(mostCubesDestroyed[2]);
//out.newLine();
out.println(mostCubesDestroyed[2]);
System.out.println(mostCubesDestroyed[2]+" Cubes GameMode 2");
//out.write(mostCubesDestroyed[3]);
//out.newLine();
out.println(mostCubesDestroyed[3]);
System.out.println(mostCubesDestroyed[3]+" Total Cubes Destroyed");
out.close();
} catch (IOException e) {
System.out.println("Error, try again!!");
}
i realize keeping the commented code makes it slightly harder to read but still i wanted to show you some things ive tried...
ive also tried to create the file the first time the app runs but to no success:
try{
File file = new File(cubesScore);
//FileReader reader = new FileReader(new File(new File("."), "score.txt"));
if(file.createNewFile()){
System.out.println("File created successfully!");
} else{
System.out.println("File already exists.");
}
} catch(IOException e){
System.out.println("An error occurred on score.txt!!");
}
so thats my problem, if anyone been here before and somehow managed to find a solution or you simply know how to produce the desired result, which is to read/write on a .txt file external to the jar(because internal leads to all sorts of issues) then pls tell me what i should do, ive seen more then a hundred post and videos and still couldnt find the desired solution.
Edit: This has been resolved below, turns out i needed a . on "/score.txt" well a . in all files.
Did you try this?:
private final String CUBES_SCORE = "./score.txt";
if you want it in a subdirectory, you have to create the subdirectory also.
Also, take a look at this: How do I create a file and write to it in Java?
I think there is some problem in your path
private final String cubesScore = "..\resF\score.txt";
hope it helps :)
Hi I am trying to set up a scanner to print out contents of a text file. Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFile {
public static void main(String[] args) {
// Location of file to read
File file = new File("CardNative.java.txt");
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
I have created a source folder in the project and put the text file in there. However I keep getting this error:
java.io.FileNotFoundException: CardNative.java.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at ScannerReadFile.main(ScannerReadFile.java:14)
You can use use System.out.println(System.getProperty("user.dir")); to see on what folder Java is looking by default for the file. If the file doesn't exist there you have to specify the entire path to the file.
This should work.
public static void main(String[] args) {
Scanner scanner = new Scanner(ScannerReadFile.class.getResourceAsStream("CardNative.java.txt"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}
You need to make sure that your file is placed in the same directory from where you're running your program. Try adding this at the top of your main function, to see what's the current directory, and if your file is actually in that directory:
System.out.println(System.getProperty("user.dir"));
new File(String pathname);
The coinstructor you are using takes filepath as an argument, absolute or relative. If it is relative, it will be the execute path/your_string.
So you should put the file to the same folder as the compiled .jar file.
File file1 = new File("text.txt");
File file2 = new File("D:/documents/test.txt");
If the programm is executing from C:/programms/myprj.jar, so
file1 will open "C:/programms/test.txt" and file2 will open "D:/documents/test.txt" independently of the executing path.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html#File(java.lang.String)
I was posting my answer in comment but I am not allowed to comment because I have no enough reputations. As in your comment, you are using back slashes in the file path. Instead use double back slashes \ OR one forward /. eg C:/java/file.txt
You should provide it the right and actual path of the file OR make sure that the file is lying there where your source is.
public class ScannerReadFile {
public static void main(String[] args) {
// Location of file to read
File file = new File("C:/Users/EastCorporation/Desktop/CardNative.java.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}