Java Reading textfile in Runnable JAR file ERROR - java

I have to make a project for school; it's a game. I load the map from a text file. Currently I do it with a scanner, but I can't manage to get it working in a Runnable JAR file without putting the res file next to the JAR file. I want to get the text file inside; it worked with BufferedImages, but the text file doesn't work. I have this code:
public String ReadTextFile(String path) throws IOException {
String HoldsText= null;
FileReader fr = new FileReader(getClass().getResource(path).toString());
BufferedReader br = new BufferedReader(fr);
while((HoldsText = br.readLine())!= null){
System.out.println(HoldsText);
}
return HoldsText;
}
path = "res/Maps/Map2.txt"
error:
java.lang.NullPointerException
at aMAZEing.TextManager.ReadTextFile(TextManager.java:22)
at aMAZEing.Map.openFile(Map.java:89)
at aMAZEing.Map.<init>(Map.java:31)
at aMAZEing.Board.<init>(Board.java:50)
at aMAZEing.Maze.<init>(Maze.java:24)
at aMAZEing.Maze.main(Maze.java:15)
file structure: http://speedcap.net/sharing/screen.php?id=files/a9/77/a977e8b487f21e67db941a96087561cd.png
This doesn't seem to work though. I've researched a lot but could not find anything that worked for me. I just need the whole text file in a string, the rest is easy with substring and so on.
EDIT!:
The resolution to this was that my path had res in it, and it didn't work because of that. I deleted the res and got "/Maps/Map2.txt" as path, now the file loads and my map is displayed again.

public static String ReadTextFile(String path) throws IOException{
String HoldsText= null;
InputStream is = getClass().getResourceAsStream(path);
InputStreamReader fr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
while((HoldsText = br.readLine())!= null){
sb.append(HoldsText)
.append("\n");
}
return sb.toString();
}
You need to append the lines and use InputStreamReader instead of FileReader

Related

How to read data from more than 1 text files using regular Expression in java?

Given more than one files in a directory
I have to read only the text files from a directory and print all the information inside it.
My Implementation:
File filepath=new File("c:/test");
Pattern p=Pattern.compile("[a-zA-Z0-9_]+.txt");
String s1[]=filepath.list();
for (int i=0;i<s1.length;i++){
Matcher m=p.matcher(s1[i]);
if(m.find()&&m.equals(s1));
System.out.println(s1[i]);
File file1=new File(s1[i]);
readFromFile(file1);
}
static void readFromFile(File filename) throws IOException{
String line = null;
FileReader fileReader = new FileReader(filename); //1
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
fileReader.close();
}
While running the above program i am getting NullPointer at position 1 as indicated in the code.
Though I know the approaches using fileList method in file class I can read all the files in a directory and I also know that i can use endsWith method in String classto read only text file.
But I wanted to know how using above implementation I can read all the data inside the text files.
Can anyone guide me on this how to correctly handle the above approach.
You probably have a problem while reading the file.
To understand what problem exactly do you have - "file not found" or maybe "insufficient read permissions" - always catch and print the exception when opening files for reading or writing (and also for reading directories):
public static void main (String[] args) {
readFromFile(new File("nonexistant.txt"));
}
public static void readFromFile(File file) {
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
for (String line = bufferedReader.readLine();
line != null;
line = bufferedReader.readLine()) {
System.out.println(line);
}
} catch (Exception ex) {
System.err.print(ex);
}
}
Here it prints the reason:
java.io.FileNotFoundException: nonexistant.txt (No such file or directory)
Once you have fixed this issue, move to the file parsing.

File Reader Method

So I wrote this file reader method that should return a string of everything that is in the file, but it isn't working properly. Writing into the file works perfectly, but this reading method doesn't. What the method does currently is it reads the last string/text added, but it does not read the file from start to finish. 'br' is my bufferedReader, which is declared somewhere else in the same class.
Here's how br is defined:
private static FileInputStream fis;
private static BufferedReader br;
and then in the constructor:
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
Here's the method:
public String readStuff(){
String line = "";
String r = "";
try{
while((line = br.readLine()) != null){
System.out.println(line + " read ");
r+= line;
}
//br.close(); JDK 7 does this automatically apparently
}catch(IOException e){
e.printStackTrace();
System.out.println("Error at readStuff!");
}
return r;
I know I'm making either a logic mistake or some obvious error, I just don't know where.
If you want to read the entire file twice, you will have to close it and open new streams/readers next time.
Those streams/readers should be local to the method, not members, and certainly not static.
Using File and FileReader You can Read / Write File From Dir.
you can get File using File class object
File file = new File("file.txt");
and After Process to read that file
FileReader fr = new FileReader(file);
There are Whole Code to read File...
File file = new File("G:\\Neon\\data.txt");
FileReader fr = new FileReader(file);
String data = "";
while((i = fr.read()) != -1)
{
data = data + (char)i;
}
System.out.println(data);

Reading a file inside jar in java

I have a situation where i have a txt file and java file bundled inside jar. I am reading txt file from java which is bundled inside jar only.
While reading file, getting FileNotFoundException in Java and where as txt file is in same folder bundled inside jar.
I am calling this Java method from a test class sample code.
public static void loadtxtfile(){
try {
InputStream in =
Utils.class.getClassLoader().getResourceAsStream("sample.txt");
File f = new File(JetUtils.class.getClassLoader().getResource("dd.js").getFile());
//OJetBase.class.getClassLoader().getResourceAsStream("logging.properties");
BufferedReader input = new BufferedReader(new FileReader(js_filepath));
StringBuffer buffer = new StringBuffer();
while ((text = input.readLine()) != null)
buffer.append(text + "\n");
java_script = buffer.toString();
}
Test call - Utils.loadtxtfile();
I tried all the options.
You cannot read resources from a jar file as a java.io.File object because they do not exist in a file system. Just use java.lang.Classloader.getResourceAsStream(String name):
Reader inputStreamReader = new InputStreamReader(
JetUtils.class.getClassLoader().getResourceAsStream("dd.js"));
BufferedReader jsReader = new BufferedReader(inputStreamReader);
StringBuilder javascript = new StringBuilder();
String input;
while ((input = jsReader.readln()) != null) {
javascript.append(input);
}

BuferredReader problems

I am having trouble reading from a file. Here is my code can anyone show me where I am wrong?
public static Map<Route, List<Service>> read(String fileName)
throws IOException, FormatException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String strLine;
while((strLine = reader.readLine())!= null)
{
/* Own Code */
}
reader.close();
}
I am having a FileNotFound Exception. May this be a the location of my file that is wrong?
You seem to want to use a resource. A resource is not accessed as a file, it is better to use it as a stream.
InputStream resourceStream = MyClass.class.getResourceAsStream(fileName);
BufferedReader myReader = new BufferedReader(new InputStreamReader(resourceStream));
Above code takes the location of your class in account, so you can simply use the fileName as is, without a path, and place the fileName next to your .java file. It will automatically be placed next to the generated .class files and - when packaged - in your .jar file.
Just as owlstead commented keep in appropriate location and try like this
URL url = ClassLoader.getSystemResource(fileName);
br = new BufferedReader(new InputStreamReader(url.openStream()));
i.e keep the file in classes folder or bundle with jar or current working directory etc.

Java read file and send in the server

I need to read contents of a file as a server, and then send the read data file, for the client so the client print it out on the Client terminal.
The problem is that I can't find a way or method to read a txt file from the current directory which my java file and txt file are existed.
Please help me.
There are many ways to read text file or file in java. It depend on you to that in which format you need to pass your file content to client side.
Here are some method to reading file in java.
1. Using BufferedReader class
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
String curLine = line;
//Process line
}
2.Using Apache Common IOUtils with the class IOUtils.toString() method.
FileInputStream inputStream = new FileInputStream("FILEPATH/FILENAME");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
3.Using the Scanner class in Java and the FileReader
Scanner in = new Scanner(new FileReader("FILENAME/FILEPATH"));
while (scanner.hasNextLine()){
//process each line in some way
String line = scanner.nextLine();
}
Scanner has several methods for reading in strings, numbers, etc...
4.In JAVA 7 this is the best way to simply read a textfile
new String(Files.readAllBytes(...))
or Files.readAllLines(...)
Path path = Paths.get("FILENAME");
List<String> allLines = Files.readAllLines(path, ENCODING);
Please refer this link for more onfomation.
You can use BufferedReader to read from a txt file.
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
here fileName is a string that contain your absolute file name.
eg : fileName = "C:\temp\test.txt";
You can read file by using BufferedReader.
File file=new File("filepath");
BufferedReader br=new BufferedReader(new FileReader(file)); //Here you create an object of bufferedreader which file read through filereader
String data=br.readLine();
while(data!=null)
{
System.out.println(data); // Writing in the console
data=br.readLine();
}
This will taking input from file and giving output to console.If you want it write in other file then use BufferedWriter.
File out=new File("outputfilepath");
BufferedWriter bw=new BufferedWriter(new FileWriter(out));
simply us bw.write() instead of System.out.println();.

Categories

Resources