I am trying to open a text file in java. I am using ubuntu 12.04. Following is my code:
package nlp;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
public class sentence {
public static void main(String[] args) {
System.out.println("hello");
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
}
}
I am using Eclipse for development. It says "FileNotFound". I have put the text file in .class as well as .java folder. Where am I going wrong?
The default execution directory in Eclipse is the root of the project folder. Put the file there or prefix the path with correct underlying folder structure.
you need to put that in try-catch because it throws IOException which is checked Exception.Put the code in try-catch or handle the exception using "public static void main(String[] args) throws IOException"
The file should be in root of the project folder as given below. Your code is working fine.
As Arnaud mentioned try this to find where Java is expecting the file:
System.out.println(new File(".").getAbsolutePath());
Related
I currently have created a Java app that will read key values from an ini file. The key value is pointing to a directory using it's absolute path (example c:\temp). I am attempting to use the String variable of the key value convert it to a File variable, then use that variable in FileReader. The issue I'm having is that the watch service will start but when I modify the watch directory with the str.txt file it throws and error and doesn't run through the switch case statement. I have also tried to use the Path variable in the bufferedReader which is why you will see it in the try statement that also didn't work, I guess I should have know that.
here are the results:
java.io.FileNotFoundException:
z:\java_apps (Access is denied)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import org.ini4j.Wini;
public class readIni {
public static String iniPath;
public static Path directory;
public static BufferedReader br;
public static void main(String[] args) throws IOException {
try {
Wini ini = new Wini(new File("z:\\java_apps\\java.ini"));
iniPath = ini.get("filepath", "filepath");
WatchService watchService = FileSystems.getDefault().newWatchService();
directory = Paths.get(iniPath);
WatchKey watchKey = directory.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
while(true) {
for (WatchEvent<?> event : watchKey.pollEvents()) {
try {
//read text into buffReader from file
Path path = directory.resolve((Path)event.context());
File file = new File(iniPath);
br = new BufferedReader(new FileReader(file));
System.out.println(file);
//create empty string, read file content line by line while the line is not empty
String str = "";
String line = br.readLine();
while (line != null) {
str= line;
line = br.readLine();
//begin switch
Could it be that the file is still open by the program when it tries to open and read it a second time?
That would explain the access denied message.
In that case I would suggest closing the file at the end of the read.
I figured it out by creating another entry in the ini file that pointed to the text file. I created another String to point to the text file instead of using the iniPath variable which must be used by Paths.get(). Originally, I was using inipath as the text file string which was giving me the errors.
try {
//outter try
//read ini file create, instantiate variables
Wini ini = new Wini(new File("z:\\java_apps\\java.ini"));
iniPath = ini.get("filepath", "filepath");
textFile = ini.get("file", "file");
Then later in the code
try {
//inner try
//read text into buffReader from file
Path path = directory.resolve((Path)event.context());
File file = new File(textFile);
I have spring boot app. I am trying to read json file which is located in my resource folder (using class loader). I have deployed my app on azure its giving me error no such file exist and when i print path it is giving me null.
I tried to create a simple Maven project to fix your issue.
My source code structure is like below.
simpleMavenProj
|-src/main/java/Hello.java
|-src/main/resources/hello.json
The content of Hello.java is as below.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class Hello {
public static void main(String[] args) throws IOException {
InputStream resourceInputStream = null;
URL resourceURL = Hello.class.getClassLoader().getResource("resources/hello.json");
if(resourceURL == null) {
System.out.println("Get the InputStream of hello.json in IDE");
resourceInputStream = new FileInputStream(Hello.class.getClassLoader().getResource("").getPath()+"../../src/main/resources/hello.json");
} else {
System.out.println("Get the InputStream of hello.json from runnable jar");
resourceInputStream = Hello.class.getClassLoader().getResourceAsStream("resources/hello.json");
}
System.out.println();
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(resourceInputStream));
String line = null;
while((line = br.readLine()) != null) {
builder.append(line+"\n");
}
br.close();
System.out.println(builder.toString());
}
}
And hello.json:
{
"hello":"world"
}
If you are developing in an IDE, run the code and the result is:
Get the InputStream of hello.json in IDE
{
"hello":"world"
}
Else for generating a runable jar file, then to run the jar file via java -jar simpleMavenProj.jar and the result is:
Get the InputStream of hello.json from runnable jar
{
"hello":"world"
}
Hope it helps. Any concern, please feel free to let me know.
I just want some files to be read and written in my Java program. So I use java.security.SecurityManager to manage this, but it seems unsatisfactory.
The Main.java file is below
import java.io.*;
import java.util.*;
public class Main {
static private final String INPUT = "in.txt";
public static void main(String args[]) throws Exception {
FileInputStream instream = null;
BufferedReader reader = new BufferedReader(new FileReader(INPUT));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
}
}
and the file /opt/java.policy like below
grant {
permission java.io.FilePermission "./out.txt", "write";
};
Then I run
java -Xss64m -Xms16m -Xmx512m -Djava.security.manager -Djava.security.policy=/opt/java.policy Main
But there are no errors, the output is what the in.txt is. I tried other file and got the same result. Why does this happen?
From the Javadoc:
Please note: Code can always read a file from the same directory it's in (or a subdirectory of that directory); it does not need explicit permission to do so.
Not that this is well-specified. Code isn't 'in' a directory: it is executed from a current working directory, and this appears to be what is meant.
I have the file allDepartments.json in a subdirectory called fixtures, to which I want to access from the Fixture.java class.
This is my Fixture.java code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public final class Fixture {
private static final String FIXTURES_PATH = "";
private final String fixture;
public Fixture(String fixtureName) throws IOException {
fixture = new String(Files.readAllBytes(Paths.get(FIXTURES_PATH + fixtureName)));
}
public final String getFixture() {
return fixture;
}
}
However every time he tries to access the file I get a java.nio.file.NoSuchFileException: allDepartments.json...
I have heard of the getResource() method and tried every combination possible of it, without success.
I need this to store multi-line strings for my JUnit tests.
What can I do?
The NIO.2 API can't be used to read files that are effectively project resources, i.e. files present on the classpath.
In your situation, you have a Maven project and a resource that you want to read during the unit test of the application. First, this implies that this resources should be placed under src/test/resources so that Maven adds it automatically to the classpath during the tests. Second, this implies that you can't use the Files utility to read it.
You will need to resort to using a traditional BufferedReader:
public Fixture(String fixtureName) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(Fixture.class.getResourceAsStream(FIXTURES_PATH + fixtureName)))) {
// do your thing with br.readLine();
}
}
Note the path given to getResourceAsStream is either relative to the current class or absolute. If the resources is located in src/test/resources/folder/allDepartments.json then a valid path would be /folder/allDepartments.json.
Add allDepartments.json to the.classpath file of the project and java should be able to pick it up.
Refer this topic if you want to know how to add a file to class path from eclipse
when you run Fixtures.java the relative path would be
../fixtures/allDepartments.json
try using this path.
Thank you all for helping and suggestions.
Thanks to you I was able to put things working, so here is the trick (which I guess only works for Maven projects):
I moved the allDepartments.json file to the default src/test/resources folder as suggested by you guys. I didn't even had to modify the pom.xml. And now everything works!
So this is my project structure now:
And the final Fixture.java code is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public final class Fixture {
private final String fixture;
public Fixture(String fixtureName) throws IOException {
fixture = this.readFile(fixtureName);
}
private String readFile(String fileName) throws IOException {
final InputStream in = this.getClass().getClassLoader().getResource("fixtures/" + fileName).openStream();
final BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
try {
return buffer.lines().collect(Collectors.joining("\n"));
} finally {
buffer.close();
}
}
public final String getFixture() {
return fixture;
}
}
I am new to freeswitch, I have tried originate command in freeswitch from fs_cli console and it was working properly. now my requirement is to execute the same from a java application.
I have tried following code
package org.freeswitch.esl.client.outbound.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Call {
Call() throws IOException {
Process pr = Runtime.getRuntime().exec("./fs_cli -x \"originate loopback/1234/default &bridge(sofia/internal/1789#192.168.0.198)\"");
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
System.out.print("success");
}
public static void main(String[] args) throws IOException {
Call call;
call = new Call();
}
}
Output
-ERR "originate Command not found!
success
please help me,
fs_cli is at "/usr/local/freeswitch/bin/" location
I have created a symbolic link in my workspace directory.
why don't you use the ESL client? It should provide much more options, and originating a call would be no problem.
Regarding your particular problem, it looks like your program tried to execute "originate" command in the shell, not the ./fs_cli. Probably it needs more Java documentation reading :)