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().
Related
Basically, I'm trying to set up a scanner that reads from a file. I know what the file name will be, but I won't know where it will be located. For testing purpose, I might know but if my teacher tests it, I won't know where the file would be located on their device.
Weirdly, I can't even seem to get it work with knowing the directory.
From what I've searched up, people say that when you just search a file using: "testdata.txt", it should search the current directory your project is in. I've tried this by putting my test file into the folder where my project is located but I still get a FileNotFoundException.
// Make scanner and read jobs into array
String fileName = "testdata.txt";
Scanner sc = new Scanner(new File(fileName));
I suggest the use of FileInputStreams and BufferedReaders. In my experience, the Scanner class is a bit strange. You could try something like this if you're only reading from the file:
File file = new File("path.txt");
List<String> jobs = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(file)) {
String line = "";
while ((line = reader.readLine()) != null) {
jobs.add(line);
}
} catch (IOException e) {
// handle errors
}
String[] jobArr = new String[jobs.size()];
jobs.toArray(jobArr);
This way you can also read on a line-to-line basis and handle each line separately.
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.
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();
}
}
}
I have coded the following for reading a txt in Java:
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String name;
String line;
System.out.println("Input file name");
Scanner inp=new Scanner(System.in);
name=inp.nextLine();
FileReader file=new FileReader(name);
BufferedReader br=new BufferedReader(new FileReader(name));
while((line=br.readLine())!=null){
System.out.println(br.readLine());
}
br.close();
}
I have a txt file that is under the same folder of my java code, its name is data.txt (which contains a list of numbers line by line), the problem that I got is that when I run this I got the following message:
Exception in thread "main" java.io.FileNotFoundException: data.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
where is the mistake? also how I can surround it with a try catch block in case the file does not exist?
I have put the System.out.println(new File(name).getAbsoluteFile); and it appears all the path thru data.txt, but I want to point by default to my current folder; should I use Scanner?
If you want to use the relative file name and you're running from an IDE like netbeans or eclipse, you file structure should look something like this
ProjectRoot
file.txt
src
build
file.txt being the relative path you're using. The IDE will first search the Project root for the file if no other directories are specified in the file path.
If youre using a scanner, you need to use the File
Scanner inp=new Scanner(System.in);
name=inp.nextLine();
File file = new File(name);
if(file.exists()) {
try {
FileReader file=new FileReader(name);
BufferedReader br=new BufferedReader(new FileReader(name));
while((line=br.readLine())!=null){
System.out.println(br.readLine());
}
br.close();
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
that should help, hope it does :)
I have a text file that gets written to a network folder and I want my users to be able to click on a jar file which will read in the text file, sort it, and output a sorted file to the same folder. But I'm having trouble formatting the syntax of the InputStream to read the file in.
When I use a FileReader instead of an InputStreamReader the following code works fine in eclipse, but returns empty when run from the jar. When I change it to InputStream like my research suggests - I get a NullPointerException like it can't find the file.
Where did I go wrong? :)
public class sort {
/**
* #param args
*/
public static void main(String[] args) {
sort s = new sort();
ArrayList<String> farmRecords = new ArrayList<String>();
farmRecords = s.getRecords();
String testString = new String();
if(farmRecords.size() > 0){
//do some work to sort the file
}else{
testString = "it didn't really work";
}
writeThis(testString);
}
public ArrayList<String> getRecords(){
ArrayList<String> records = new ArrayList();
BufferedReader br;
InputStream recordsStream = this.getClass().getResourceAsStream("./input.IDX");
try {
String sCurrentLine;
InputStreamReader recordsStreamReader = new InputStreamReader(recordsStream);
br = new BufferedReader(recordsStreamReader);
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return records;
}
private static void writeThis(String payload){
String filename = "./output.IDX";
try {
BufferedWriter fr = new BufferedWriter(new FileWriter(filename));
fr.write(payload);
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
getResourceAsStream() loads files from the classpath. If you are running this from the command line, you would need the current directory (.) on the classpath. If you want to load arbitrary files from the file system, you should use FileInputStream (or FileReader to save having to subsequently wrap the input stream in a reader).
Using a FIS to get a file inside a jar will not work since the file is not on the file system per se. You should use getResrouceAsStream() for that.
Also, to access a file inside a jar, you must add an "!" to the file path. Is the file inside the jar? If not, then try a script to start the jar after passing the classpath:
start.sh
java -cp .:your.jar com.main.class.example.run
Execute this script (on linux) or modify it as per your platform.
Also, you can use the following code to print out the classpath. This way you can check whether your classpath contains the file?
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
// Get the URLs
URL[] urls = ((URLClassLoader) sysClassLoader).getURLs();
for (int i = 0; i < urls.length; i++) {
System.out.println(urls[i].getFile());
}
}