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.
Related
I want to change the substring value of a text file everytime.
Below Hello.txt file with below datas:-
ID 422686 658658 987451
when I am hardcoding this value is replace by new number like,
modifyFile("Hello.txt", "422686", RandomStringUtils.randomNumeric(6));
The value is getting change and new randomNumeric number in this position.Below Text file datas is fixed so I dont need to hardcode the number everytime so looking to change the value from subsring concept ,I tried this but while passing the changevalue ,getting Null pointer exception
changevalue= oldContent.substring(7, 12);
Below is my full code ,Please check and update
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.lang3.RandomStringUtils;
public class ModificationTextFile
{
static String changevalue;
static void modifyFile(String filePath, String oldString, String newString)
{
File fileToBeModified = new File(filePath);
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(fileToBeModified));
//Reading all the lines of input text file into oldContent
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
changevalue= oldContent.substring(7, 12);
line = reader.readLine();
System.out.println("oldContent"+oldContent);
System.out.println("key"+changevalue);
System.out.println("line"+line);
}
//Replacing oldString with newString in the oldContent
String newContent = oldContent.replaceAll(oldString, newString);
//Rewriting the input text file with newContent
writer = new FileWriter(fileToBeModified);
writer.write(newContent);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
//Closing the resources
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
modifyFile("Hello.txt", "422686", RandomStringUtils.randomNumeric(6));
//modifyFile("coln.txt", changevalue, RandomStringUtils.randomNumeric(6));//java.lang.NullPointerException
System.out.println("done");
}
}
You need to read about substring method.
The first parameter is beginIndex, which is 3 in your case. Also, the second parameter is endIndex, which is the index after the last character in your specified string, which is 9 in your case.
So, you should write it as follows: changevalue= oldContent.substring(3, 9);
I hope it helps you solve your problem.
first of all the changevalue= oldContent.substring(7, 12); line should be after the while loop
i think the easiest thing to do is to get the substring and replace the first occurrence of the substring you got in the text
changevalue= oldContent.substring(7, 12);
oldContent.replaceFirst(changevalue,"new text value");
for the NullPointerException you have to test if the text is not null before calling the substring method
Actually, I am assigned a task where I have a xyz.txt/CSV file which will basically have numeric values and I am supposed to pass it through BUFFERED READER then split those values and finally parse them.
So I have a Java code can body help me with it.
package javaapplication12;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class JavaApplication12 {
public static void main(String[] args) {
String count= "F:\\Gephi\\number.txt";
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(count);
br = new BufferedReader
// AT THIS POINT THERE SHOULD BE SOME THING THAT COUNTS NUMBER OF LINES USING COUNT++ OR SOMETHING LIKE THIS//
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
// COMING TO THIS POINT THE ABOVE VALUES OF .TXT FILE SHOULD BE SPLIT USING SPLIT PARAMETER//
// AFTER SPLITTING THE SPLIT VALUE SHOULD BE KEPT IN AN ARRAY AND THEN EVENTUALLY PARSED//
Or IF Anybody can rewrite the code in another way of the above-stated problem, it shall also be appreciated.
Here is my solution with Java 8:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
public class BR {
public static void main(String[] args) {
String fileName = "br.txt";
//for the csv format
String regex = ", ";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
List<String[]> lines = br.lines()
.map(line -> line.split(regex))
.collect(Collectors.toList());
parse(lines);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void parse(List<String[]> lines) {
//Do your stuff here
}
}
The initialization of the BufferedReader is in the try block (this approach is called try with resources), since BufferedReader implements AutoCloseable (an interface), so in case an exception is thrown the reader will close.
The br.lines() method returns all lines from the file.
In the map function you are passing a line that is rad in a lambda. The line is split using the split variable (for CSV format it is ', ') and is returned and collected.
The result is a List of arrays of String which can be changed in the body of the map function.
For more clarification I suggest you check some Java 8 tutorials and you will fully understand what is going on.
This solution might not be appropriate for your knowledge level (I guess), but hope it inspires you to check some fancier and modern approaches.
Have a nice day.
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
The text file looks something like this:
keyword12x:
=========
Acon:
a1
x2
z3
Bcon:
c1
e2
w3
r4
and so on... (always the same sheme and a lot of keywords in the file)
I need a function that I can pass keyword12x and the signal type that I'm looking for which searches through the text file and returns the corresponding Acon or Bcon singnals
Exaple declaration:
public string searchKey(string keyword, string type){
....
}
a call like:
search("keyword12x", "Acon")
outputs:
a1
x2
z3
(type = Bcon would obviously give c1, e2, w3, r4)
EDIT: This is what "I have".. (It's not what I want and only for testing porpose)
As you can see it's searching the "keyword12x" line and I'm stuck there.
import java.io.File;
import java.util.Scanner;
public class ReadText
{
public static void main(String[] args) throws Exception
{
File file =
new File("C:\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()){
String line = sc.nextLine();
if(line.contains("keyword12x")){
System.out.println(line);
}
}
}
}
EDIT2:
> step by step "in english":
> 1. go trough lines
> 2. untill you find "keyword12x"
> 3. keep going through lines (from that point !)
> 4. find "Acon:"
> 5. go next line
> 6. start printing out and go next line (loop)
> 7. until line = "Bcon:" appears
> 8. go next line
> 9. start printing out and go next line (loop)
> 10. untill an empty line appears
EDIT3:
Lets resume: I want to search for a line containing the keyword (with a ':' appended), then (after that line) search for a line containing the given type (also followed by ':') and then gather all following lines up to, but not including a line that ends with ':' or empty line. [summary by #Carlos Heuberger]
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Demo
{
static String readLine = "";
String ch ;
static File f = new File("/home/admin1/demoEx");
public String searchKey(String keyword, String type) throws IOException
{
ch = type.toLowerCase().substring(0, 1);
BufferedReader b = null;
try {
b = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Reading file using Buffered Reader");
while ((readLine = b.readLine()) != null)
{
if(readLine.contains(ch))
{
System.out.println(readLine);
}
}
return readLine;
}
public static void main(String args[])
{
try {
String x = (new Demo()).searchKey("keyword12x","Bcon");
} catch (IOException e) {
e.printStackTrace();
}
}
}
try this one.
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);
}