Getting an exception when putting string before while - java

I am using the following code to get data from a file
try {
InputStreamReader inputStreamReader = new InputStreamReader(openFileInput(TEXTFILE));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String string;
StringBuilder stringbuilder = new StringBuilder();
while ((string=bufferedReader.readLine())!=null){
stringbuilder.append(string);
}
EditText.setText(stringbuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
It works but
when I put the string=bufferedReader.readLine() before While, I get an exception : java.lang.OutOfMemoryError

You're reading a line from the BufferedReader, and storing the result in string. After that, you check if string != null, and if not, you append string to stringbuilder. You're repeating this until string == null.
The confusion here might be the comparison of an assignment statement:
while ((string = bufferedReader.readLine()) != null) { ... }
This is a short notation of the following:
string = bufferedReader.readLine();
while (string != null) {
...
string = bufferedReader.readLine();
}

Related

File to String Null Pointer Exception

I'm trying to pass the contents of a file into a method as a String and encountering a Null pointer exception. I'm converting the file into a String like so:
import java.io.*;
public class FileHandler {
String inputText = null;
public String inputReader() {
StringBuilder sb = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("in.txt"))));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
String inputText = sb.toString();
//System.out.println(inputText);
}
br.close();
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
}
return inputText;
}
}
This is working fine for me in terms of converting the file to a String, but when I try and pass the output of this into another method I get a null pointer exception here:
char[][] railMatrix = new char[key][inputText.length()];
I copied the contents of the file and passed it in as a normal String like so;
String plain = "The text from the file"
int key = 5;
int offset = 3;
String encrypted = rf.encrypt(plain, key, offset);
System.out.println(encrypted);
String unencrypted = rf.decrypt(encrypted, key, offset);
System.out.println(unencrypted);
And it worked fine. But
String plain = fh.inputReader();
Does not.
So inputReader() seems to work, the methods it's being passed into work, but I'm clearly missing something.
A nod in the right direction would be greatly appreciated, thanks friends.
Your result is stored in a local variable "inputText" and you are returning instance level variable which is null and is never reassigned. Remove String type as below and it should work:
while ((line = br.readLine()) != null) {
sb.append(line);
inputText = sb.toString();
//System.out.println(inputText);
}

Get specific text from a .txt file

I want to get information from a script so i used this function
public static HashMap<String, String> getEnvVariables(String scriptFile,String config) {
HashMap<String, String> vars = new HashMap<String, String>();
try {
FileInputStream fstream = new FileInputStream(scriptFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
String var= "if [ \"$1\" = \""+config +"\" ] ; then";
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// use a Scanner to parse the content of each line
// exclude concatenated variables (export xx:$xx)
if (strLine.startsWith("export") && !strLine.contains("$")) {
strLine = strLine.substring(7);
Scanner scanner = new Scanner(strLine);
scanner.useDelimiter("=");
if (scanner.hasNext()) {
String name = scanner.next();
String value = scanner.next();
System.out.println(name+"="+value);
vars.put(name, value);
}
}
}
However i want to begin reading from a particular line which is
if [ \"$1\" = \""+config +"\" ] ; then
the problem is that when a line begins with a space the program considers that the file have ended !
So how can i fix it and make the program pars to the end of file ?
considering that the line could begin with more thant one space
thx
You may try to trim the irrelevant spaces from every line ?
while ((strLine = br.readLine().trim()) != null) {...}
Edit : don't do that (thanks Joop Eggen!) or you'll have a nice NPE...). Try:
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
...
}
Sounds for me like you should use regular expressions (e.g. use the String.matches() method). They also can extract strings or substrings (see: another Stackoverflow article).
There is also an excellent introduction by Lars Vogella about regular expressions in Java. Oracle compiled also a Tutorial/Lesson about that topic.
May be this snippet helps a bit (uses org.apache.commons.io.LineIterator):
public void grepLine(File file, String regex)
{
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try
{
while (it.hasNext())
{
String line = it.nextLine();
if(line.matches(regex))
{
//...do your stuff
}
}
}
finally
{
LineIterator.closeQuietly(it);
}
}
The regex might be something like (note: havn't checked it - especially the backslashes):
String regex="^\\s*if\\s+\\[\\s+\\\"\\$1\\\" = \\\""+config +"\\\" \\] ; then";
Before all else: leave out DataInputStream, more Java Object specific.
boolean started = false;
while ...
if (!started) {
started = strLine.matches("\\s*...\\s*");
} else {
...
Reg ex \\s* stand for zero or more white-space characters (tab, space).
I found a solution which i share with you .
public static HashMap<String, String> getEnvVariables(String scriptFile ,String config1,String config2) {
HashMap<String, String> vars = new HashMap<String, String>();
BufferedReader br = null;
try {
FileInputStream fstream = new FileInputStream(scriptFile);
br = new BufferedReader(new InputStreamReader(fstream));
String strLine = null;
String stopvar = config2;
String startvar =config1;
String keyword = "set";
do {
if (strLine != null && strLine.contains(startvar)) {
if (strLine.contains(stopvar)) {
return vars;
}
while (strLine != null && !strLine.contains(stopvar)) {
strLine = br.readLine();
if (strLine.trim().startsWith(keyword)&& !strLine.contains("$")) {
strLine = strLine.trim().substring(keyword.length())
.trim();
String[] split = strLine.split("=");
String name = split[0];
String value = split[1];
System.out.println(name + "=" + value);
vars.put(name, value);
}
}
}
} while ((strLine = br.readLine()) != null);
} catch (Exception e) {
Status status = new Status(Status.ERROR, Activator.PLUGIN_ID,
IStatus.ERROR, e.getMessage(), e);
Activator.getDefault().getLog().log(status);
}
return vars;
}
thanks for helping !

Writing multiple queries from a test file

public static void main(String[] args) {
ArrayList<String> studentTokens = new ArrayList<String>();
ArrayList<String> studentIds = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File("file1.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0) && (!strLine.contains("#"))) {
String[] students = strLine.split("\\s+");
studentTokens.add(students[TOKEN_COLUMN]);
studentIds.add(students[STUDENT_ID_COLUMN]);
}
}
for (int i=0; i<studentIds.size();i++) {
File file = new File("query.txt"); // The path of the textfile that will be converted to csv for upload
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replace("sanid", studentIds.get(i)).replace("salabel",studentTokens.get(i)); // Here the name "sanket" will be replaced by the current time stamp
FileWriter writer = new FileWriter("final.txt",true);
writer.write(newtext);
writer.close();
}
fstream.close();
br.close();
System.out.println("Done!!");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
The above code of mine reads data from a text file and query is a file that has a query in which 2 places "sanid" and "salabel" are replaced by the content of string array and writes another file final . But when i run the code the the final does not have the queries. but while debugging it shows that all the values are replaced properly.
but while debugging it shows that all the values are replaced properly
If the values are found to be replaced when you debugged the code, but they are missing in the file, I would suggest that you flush the output stream. You are closing the FileWriter without calling flush(). The close() method delegates its call to the underlying StreamEncoder which does not flush the stream either.
public void close() throws IOException {
se.close();
}
Try this
writer.flush();
writer.close();
That should do it.

java: Using Buffered Reader and checking if String is null

why doesn´t if (txtLine == null) { break; };work? or maybe the correct answer is why does it still set the string txtLine to null (literally). The way I understand it, it should break the moment the string is null? I don´t want it to set the string to "null". but stop when there are no more lines in the *.txt file
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while (true) {
// Reads one line.
println(txtLine);
if(txtLine == null){
break;
};
txtLine = txtReader.readLine();
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
the txtFile variable is defined as an IVAR
private int nChars = 0;
private String txtLine = new String();
private ArrayList <String> array = new ArrayList <String>();
I think the ordering of when you break and when you change the value of txtLine to be the next line read from the file is backwards, your code should look something like:
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while (true) {
// Reads one line.
println(txtLine);
txtLine = txtReader.readLine();
// check after we read the value of txtLine
if(txtLine == null){
break;
}
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
But this is a much more concise (and I think, clearer) form:
try{
BufferedReader txtReader = new BufferedReader (new FileReader ("test.txt"));
while ((txtLine = txtReader.readLine()) != null) {
// Reads one line.
println(txtLine);
nLines(txtLine);
}
txtReader.close();
} catch (IOException ex) {
throw new ErrorException(ex);
}
Where while ((txtLine = txtReader.readLine()) != null) sets txtLine to the next line, and then checks that txtLine is not null before continuing.

Return the text of a file as a string? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create a Java String from the contents of a file
Is it possible to process a multi-lined text file and return its contents as a string?
If this is possible, please show me how.
If you need more information, I'm playing around with I/O. I want to open a text file, process its contents, return that as a String and set the contents of a textarea to that string.
Kind of like a text editor.
Use apache-commons FileUtils's readFileToString
Check the java tutorial here -
http://download.oracle.com/javase/tutorial/essential/io/file.html
Path file = ...;
InputStream in = null;
StringBuffer cBuf = new StringBuffer();
try {
in = file.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
cBuf.append("\n");
cBuf.append(line);
}
} catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}
// cBuf.toString() will contain the entire file contents
return cBuf.toString();
Something along the lines of
String result = "";
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Here's where you get the lines from your file
result += dis.readLine() + "\n";
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
String data = "";
try {
BufferedReader in = new BufferedReader(new FileReader(new File("some_file.txt")));
StringBuilder string = new StringBuilder();
for (String line = ""; line = in.readLine(); line != null)
string.append(line).append("\n");
in.close();
data = line.toString();
}
catch (IOException ioe) {
System.err.println("Oops: " + ioe.getMessage());
}
Just remember to import java.io.* first.
This will replace all newlines in the file with \n, because I don't think there is any way to get the separator used in the file.

Categories

Resources