I've a txt file. In there are rules and I have to get everything between the brackets in a separate file. But I don't even get it shown in the console.
I already tried many methods, but i always get some errors.(outlined code)
With the solution right now, it just showing nothing in the console. Does anyone know why?
The brackets are always in the same line as "InputParameters" i tried something with that, at the end of the code.
The solutions that are outlined won't work. Maybe someone got an idea?
with that code below i get the following error :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at java.lang.String.substring(Unknown
Source) at blabla.execute.main(execute.java:17)
here some content from the txt file:
dialect "mvel"
rule "xxx"
when
InputParameters (xy <= 1.124214, xyz <= 4.214214, abc <= 1.12421, khg <= 1.21421)
then
Ty
Here is the code:
public class execute {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:..."));
java.lang.String line;
line = br.readLine();
while ((line = br.readLine()) != null) {
System.out.println(line.substring(line.indexOf(("\\("), line.indexOf(("\\)")))));
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1 at java.lang.String.substring(Unknown
Source) at blabla.execute.main(execute.java:17)
This exception means that -1 was passed to substring() method. This -1 is produced by indexOf() when it doesn't find anything.
Does all your lines contain brackets? There should be check if the brackets are present in the line.
while ((line = br.readLine()) != null) {
if(line.indexOf(("\\(") != -1 && line.indexOf(("\\)") != -1) {
System.out.println(line.substring(line.indexOf(("\\("), line.indexOf(("\\)")))));
}
}
the problem is if you want to get the index of a string (indexOf()) in a string in which the searched string doesnt exist, indexOf returns -1 and if the method substring receives the argument -1 then it throws a StringIndexOutOfBoundsException. I suggest to check first if a line contains "InputParameter" since you said this word is always in the same line and then you get the string inside the brackets by using the methods subtring and indexOf.
this one works for me
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileRead {
public static void main(String[] args) {
final String filename = "$insertPathToFile$";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
while(line != null){
if (line.contains("InputParameters")) {
System.out.println(line.substring(line.indexOf("(")+1, line.indexOf(")")));
} // end if
line = br.readLine();
} // end while
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
br.close();
} catch (IOException e) {}
} // end try
} // end main
} // end class
Related
I'm trying to write a method for a program that only reads the last line of the text file, but I can't find out what the issue is and I have been searching for a while. Any help would be amazing.
public String getLastLine(String path) throws IOException {
String st;
String ot = null;
try {
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
while ((st = br.readLine()) != null) {
ot = st;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return ot;
}
Everything I have been able to find tells me to create a string and set it to null or to set it to "", but this isn't working at all for me. I keep getting this error code
org.junit.ComparisonFailure: expected:<[BZHbzAauZi]> but was:<[]>
I tried to return the last line of a text file but it only returns as a empty space.
while ((st = br.readLine()) != null)
{
if(st.isBlank()) {
continue;
}
ot = st;
}
Will preserve the last-read, non-blank line.
Somehow my if loop using a substring to check a .txt file is causing problems. Without the if loop, everything works fine. But with it, it seems that an empty line in the text file is causing it to crash. It is working until the first empty line in the file, and then I get this error. What could I do about that?
code:
public class S1_Blockchain extends ConsoleProgram {
public void init() {
setSize(400, 250);
setFont("Arial-bold-18");
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("block_chain.txt"));
while((line = br.readLine()) != null){
if(line.substring(0,1).equals("T") || line.substring(0,1).equals("G")) {
System.out.println(line);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You might want to also check empty string:
if( !line.trim().isEmpty() && (line.substring(0,1).equals("T") || line.substring(0,1).equals("G"))) { ... }
You then might also want to refactor the code to make it more readable:
public class S1_Blockchain extends ConsoleProgram {
public void init() {
setSize(400, 250);
setFont("Arial-bold-18");
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("block_chain.txt"));
while((line = br.readLine()) != null){
if(shouldConsider(line)) {
System.out.println(line);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private boolean shouldConsider(String line){
return !line.trim().isEmpty()
&&
(line.substring(0,1).equals("T") || line.substring(0,1).equals("G"));
}
So you tested your first edge-case for empty string "" (unhappy path).
Next you can avoid effective empty cases by using trim() (remove surrounding white-spaces):
so spaced input like " Trouble Centered " becomes trimmed `"Trouble Centered" (so that starting with a "T" which could be wanted).
and blank lines like " " become empty string "" (which will break some tests)
br = new BufferedReader(new FileReader("block_chain.txt"));
while((line = br.readLine()) != null){
line = line.trim(); // remove white-spaces; blank line results as empty
if (line.isEmpty()) {
// might handle or ignore this case
}
firstChar = line.charAt(0); // expresses intend better than substring
if (Set.of('T', 'G').contains(firstChar) { // the Set improves readability for condition
System.out.println(line);
}
}
Alternatives for Testing Strings
A) separate tests:
could also test an empty (not even spaces) or blank (only spaces) with line.isBlank()
could also test the start of a string with line.startsWith("T")
B) all in one (your case):
with a regular expression catching all cases: line.matches("^\\s*(G|T)")
Besides checking if your String is null you also have to check if it is an empty String (""). You can check it as line.trim().legth() == 0; or line.isEmpty() but also there is Apache Utils called StringUtils. There there is a method isBlank(String str) that checks in one go if String is null or blank. That is what I would recommend
I am trying to read file with BufferedReader and at the time of spliting each line of file I want to convert string data at 8th position to be converted to float.(count starts from 0 data)
below is my code :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TestFloat {
static BufferedReader bin;
String line;
void sumAmount() throws IOException //Perform calculation
{
bin = new BufferedReader(new FileReader("D:\\Extras\\file.txt"));
//String firstline = bin.readLine();
while ((line = bin.readLine()) != null)
{
String data[] = line.split(",");
//System.out.println(data[8]);
System.out.println(Float.valueOf(data[8]));
//System.out.println(java.lang.Float.parseFloat(data[8]))
}
}
public static void main(String[] args)
{
TestFloat ts = new TestFloat();
try {
ts.sumAmount();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for this code I am getting exception as below :
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.lang.Float.parseFloat(Float.java:451)
at java.lang.Float.valueOf(Float.java:416)
at TestFloat.sumAmount(TestFloat.java:17)
at TestFloat.main(TestFloat.java:24)
one sample line of file.txt is :
20,20160518,262,20160518,00,F&O ABC DEBIT F 160518,000405107289,000405006220,5000000.00,5000000.00,0.00,,
I have tried with parseFloat and valueOf both function but it shows exception. What is the reason behind the fail?
java.lang.NumberFormatException: empty String
as the error states you're attempting to parse an empty string.
one solution is to use an if statement to guard off the NumberFormatException(only for empty strings that is, you could still get the NumberFormatException for unparseable strings).
if(data[8] != null && data[8].length() > 0){
System.out.println(Float.valueOf(data[8]));
System.out.println(java.lang.Float.parseFloat(data[8]));
}
you'll need to go through the debugger step by step and see what is the real issue behind it.
I beginner to Java, I want to read and write a string from a text file, I tried with my idea but its not work. It show me an error...
See below my code:
import java.util.*;
import java.io.*;
public class Uptime {
public static void main(String[] args) {
FileWriter fileWriter = null;
try
{
double Oldtime=0;
BufferedReader read=new BufferedReader(new FileReader("C:/eGurkha/agent/sample/UptimeRecord.txt"));
if(read.readLine()!=null)
{
Oldtime=Double.parseDouble(read.readLine());
System.out.println("Old System Time is :"+Oldtime);
}
else
{
Oldtime=0;
}
Process p=Runtime.getRuntime().exec("C:\\eGurkha\\lib\\vmgfiles\\win\\VmgUptimeTest.exe");
BufferedReader rd=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=rd.readLine();
System.out.println(line);
String[] word=line.split("=");
fileWriter=new FileWriter("C:/eGurkha/agent/sample/UptimeRecord.txt");
fileWriter.write(word[1]);
System.out.println("New System Time is :"+word[1]);
System.out.println("String Written");
fileWriter.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
This is the error, which is shown by the above code.
Exception in thread "main" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1008)
at java.lang.Double.parseDouble(Double.java:540)
at com.kavi.tasks.Uptime.main(Uptime.java:17)
Please tell me the idea...
The problem is the code
if(read.readLine()!=null)
{
Oldtime=Double.parseDouble(read.readLine());
You read line (it isn't null) but then you read the next line when try to parse (and the next line is empty).
Use instead
String line=read.readLine();
if(line!=null)
{
Oldtime=Double.parseDouble(line);
if(read.readLine()!=null)
{
Oldtime=Double.parseDouble(read.readLine());
System.out.println("Old System Time is :"+Oldtime);
}
You're reading the line in the if-statement. Then you read the next line in the parseDouble-statement. This is reference is null. So you've to save the line in the if statement.
String line = null;
if((line = read.readLine()) != null) {
double time = Double.parseDouble(line);
...
}
Try to Pass the String in the if statement ,so that the compile would know that which type of object he needs to pass.
if(String=....
.....){
}
problem is with
if(read.readLine()!=null)
{
Oldtime=Double.parseDouble(read.readLine());
System.out.println("Old System Time is :"+Oldtime);
}
readLine() internally calls lineNumber++ which means you go to next line of your file when you call this. Instead use
if((line = read.readLine()) != null)
{
Oldtime=Double.parseDouble(line);
System.out.println("Old System Time is :"+Oldtime);
}
I have a BufferedReader iterating through the lines of a CSV file; when it gets to the end of the file, it returns the following error:
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:992)
How do I get the reader to realize it reached the end of file and input is null instead of empty? I've checked the file and there is no whitespace at the end of the last line.
Code:
File filReadMe = new File(inputFile);
BufferedReader brReadMe = new BufferedReader(new InputStreamReader(new FileInputStream(filReadMe), "UTF-8"));
try
{
String strLine;
while ((strLine = brReadMe.readLine()) != null)
{
System.out.println(strLine);
//place the line into CsvRecordFactory
int record = csv.processLine(strLine, input);
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
//Close the BufferedReader
try {
if (brReadMe != null)
brReadMe.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
You can simply modify your code this way:
while ((strLine = brReadMe.readLine()) != null)
{
if (!strLine.isEmpty()) {
System.out.println(strLine);
//place the line into CsvRecordFactory
int record = csv.processLine(strLine, input);
}
}
This way, your code will ignore all empty lines, not only those at the end of your file.
The problem isn't the end of file. The problem is that you are processing a blank line as though it wasn't blank. That could conceivably happen anywhere, not just as a final line before EOF. Check the line for emptiness before you start parsing it.
if the end of your file is a newline, try backspacing it to the end of the previous line and see if you still get the error
Try to give it a small if condition to check whether the string is empty or not.
Version 1: Check if string is empty
while ((strLine = brReadMe.readLine()) != null)
{
if(!strLine.isEmpty()){
System.out.println(strLine);
//place the line into CsvRecordFactory
int record = csv.processLine(strLine, input);
}
}
I also have version 2 of code, which checks if string is number otherwise if they are characters or empty or anything else, the code inside if is going be ignored
while ((strLine = brReadMe.readLine()) != null)
{
if(strLine.matches("\\d+")){
System.out.println(strLine);
//place the line into CsvRecordFactory
int record = csv.processLine(strLine, input);
}
}