Goal: to read contents of a file that is in my root directory. Eventually I want to be able to read a .conf file, but right now I am testing with a .txt file since it seems easier to begin with..
I am using the open source Shell file from an XDA video to navigate to my root directory. For reference, the file is located at: "/data/misc/joke.txt"
This is the code in my main method:
String command[]={"su","-c","ls /data/misc"};
Shell shell = new Shell();
String output = shell.sendShellCommand(command);
try {
read(output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So basically all that is doing is granting SU permission, and then navigating to the /data/misc folder. Then in the Shell() class, I scan through each file and search for the text file I want. This might be redundant since I expect the text file to be "joke.txt" EVERYTIME. Anyways, I am having an issue with this block of code, the read() method:
public void read(String out) throws Exception{
File yourFile = new File("/data/misc", out);
FileReader file = new FileReader(yourFile);
BufferedReader reader = new BufferedReader(file);
String line;
String text = "";
line = reader.readLine();
while (line != null) {
text += (line);
line = reader.readLine();
}
setNewTextInTextView(text);
}
It crashes at this line:
FileReader file = new FileReader(yourFile);
Any tips?
Related
I cant get rid of this FileNotFound error even though the file exists. Any ideas? (There are hundreds of lines of code so im just going to paste the chunk around the error, if this is an issue I can post more)
// method start
System.out.println(System.getProperty("user.dir"));
File names = new File("src/guiProject/nameList");
System.out.println(names.getAbsolutePath());
// !!!! V ERROR OCCURS HERE V !!!!
BufferedReader br = new BufferedReader(new FileReader(names));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String allNames = sb.toString();
userListArea.setText(allNames);
} catch (IOException o) {
o.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//method end
Probably your Windows does not show file extensions; nameList.txt?
Otherwise the working directory is not in the project directory with subdirectory src.
A FileReader uses the default Charset, so the file is not portable. If you run the application on another platform then the developer's, the encoding is wrong.
Best use UTF-8, full Unicode.
Then the reading strips the line ending:
while (line != null) {
sb.append(line).append("\r\n");
line = br.readLine();
}
You could do:
Path names = Paths.get("src/guiProject/nameList.txt"); // File
Path names = Paths.get(
MyClass.class.getResource("/guiProject/nameList.txt").toURI()); // Resource
String allNames = new String(Files.readAllBytes(names), StandardCharsets.UTF_8);
userListArea.setText(allNames);
If it is a read-only file, stored in the application jar, it is a resource rather than a disk File.
Maybe you are not in the folder you think.
Create a file with a dummy name and get the absolute path of this file, this way you can doublecheck you are where you think you really are.
I have a program that saves on a file. The current code is set for the file to save on a specific path, but when I run the program from a different computer the program doesn't work and I need to change the path everytime.
public CreateCustomer() {
initComponents();
ArrayList<String> ConsIDList = new ArrayList<String>();
String csvFileToRead = "E:\\ryan_assignment_sit2\\ConsID\\consID.csv"; // Reads the CSV File.
BufferedReader br = null; // Creates a buffer reader.
String line = "";
String splitBy = ","; // Reader Delimiter
try {
br = new BufferedReader(new FileReader(csvFileToRead)); // Buffer Reader with file name to read.
Scanner reader = new Scanner(System.in);
while ((line = br.readLine()) != null) { //While there is a line to read.
reader = new Scanner(line);
reader.useDelimiter(splitBy);
while (reader.hasNext()) { // While there is a next value (token).
ConsIDList.add(reader.next());
}
}
} catch (FileNotFoundException exception) { // Exception Handler if the File is not Found.
exception.printStackTrace();
} catch (IOException exception) { // Input/Output exception
exception.printStackTrace();
} finally {
if (br != null) {
try {
br.close(); // Close the Scanner.
} catch (IOException exception) {
exception.printStackTrace();
}
}
I placed the file in the a subfolder in the program with the name ConsID and I tried changing the path file to
String csvFileToRead = "..\\ConsID\\consID.csv";
But the file can't be read from the program.
String csvFileToRead = "E:\ryan_assignment_sit2\ConsID\consID.csv";
The above path will only be applicable to windows. If you execute the program in linux environment you will get an Filenotfoundexception. Eventhough you change the file, again you are hardcoding the file path.
Better you can get it as runtime parameters so that the program will be executed irrespective of OS.
If you are running you program from command line then you can place the csv file in your classpath (root folder where the class files are generated) and refer to it as below:
BufferedReader br = new BufferedReader(ClassLoader.getResourceAsStream("consID.csv"));
I am trying to open a file in JAVA using BufferedReader but it cannot open the file. Here is my code
public static void main(String[] args) {
try
{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = null;
while ((reader.readLine()!= null))
{
line = reader.readLine();
System.out.println(line);
}
reader.close();
}
catch(Exception ex)
{
System.out.println("Unable to open file ");
}
}
It goes to the exception and prints Unable to open file. Any suggestions why I cannot able to read it.
If you want to be more nearly modern, try the Java 7 solution, taken from the Paths Javadoc:
final Path path = FileSystems.getDefault().getPath("test.txt"); // working directory
try (final Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
} // No need for catch; let IOExceptions bubble up.
// No need for finally; try-with-resources auto-closes.
You'll need to declare main as throwing IOException, but that's okay. You have no coherent way of handling IOException anyway. Just read the stack trace if an exception is triggered.
I don't know why this happened, but the problem seemed that I did not enter the complete path for the file even though the file was in the same folder. Ideally if the file is in the same folder then I wouldn't need to enter the entire pathname.
Try doing a check if it exists first:
File file = new File("test.txt");
if (!file.exists()) {
System.err.println(file.getName() + " not found. Full path: " + file.getAbsolutePath());
/* Handling code, or */
return;
}
BufferedReader reader = new BufferedReader(new FileReader(file));
/* other code... */
I have an eclipse project and in one folder there is a text file "conf.txt". I can read and write the file when I use the path on my Computer. But I have to write my own folders there as well, not only the workspace folders.
So know I want to commit the program for others, but then the path I put in the program won't work, because the program is running on a different computer.
What I need is to be able to use the file with only the path in my workspace.
If I just put in the path, which is in the workspace it won't work.
This is how my class File looks like.
public class FileUtil {
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = "";
while ((line = reader.readLine()) != null) {
returnValue += line + "\n";
}
reader.close();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
return returnValue;
}
public void writeTextFile(String fileName, String s) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
try {
output.write(s);
}
finally {
output.close();
}
}
}
I hope someone knows what to do.
Thanks!
I am not sure but I attached the screen shot with little bit explanation. Let me know if you have any question.
Your project is root folder here and images as resources folder from where you can access the file using relative path.
// looks for file in root --> file.txt
scan = new Scanner((new File("file.txt")));
// looks for file in given relative path i.e. root--> images--> file.txt
scan = new Scanner((new File("images/file.txt")));
If you want your configuration file to be accessed through a relative path, you shouldn't need to add anything to the front of it. Assuming you're using a bufferedReader, or something of the sort it would look as simple as: br = new BufferedReader(new FileReader("config.txt"));
This will cause a search of the runtime directory, making it so you don't have to fully qualify the path to your file. That being said you have to ensure your config.txt is within the same directory as your executable.
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());
}
}