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);
}
Related
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
I want to extract the first column in a file using the delimiter "," and save it into a new File.
Output generates this exception :
Exception in thread "main" java.lang.NullPointerException
at Extract.main(Extract.java:26)
Here is the code that I used butI am not sure if it is correct or not:
public class Extract {
public Extract(){
}
public static void main(String[] args) {
BufferedReader in = null;
try {
BufferedWriter out = new BufferedWriter(new FileWriter("/home/omar/Téléchargements/nursery.tmp"));
in = new BufferedReader(new FileReader("pima.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
if (splited.length > 0)
{
out.append(splited[0].toString());
out.newLine();
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
File f = new File("prima.txt");
f.delete();
File f2 = new File("pima.tmp");
f2.renameTo(new File("pima.txt"));
}
}
Remove the first line, ie read = in.readLine();, from inside your while() loop.
The problem is that you are reading the line when you are checking the while condition and inside while loop you are reading a line again (but this time a new line, because readLine not only reads a line but also moves the reading pointer to next line) so you are getting the next line.
Once you are past the end of the file you get null instead of a line, that is why you are getting Exception.
public static void main(String[] args) throws MalformedURLException, IOException
{
// TODO code application logic here
URL link1 = new URL("xmlFileHere");
InputStream xml = link1.openStream();
InputStreamReader reader = new InputStreamReader(xml);
BufferedReader reader1 = new BufferedReader(reader);
while(reader1.readLine()!= null)
{
System.out.println(reader1.readLine());
}
}
Hello. As you can see my BufferedReader is not reading the whole online XML file, I don't know why. Any idea why this happens?
Thank you.
while(reader1.readLine()!= null) // reading here
{
System.out.println(reader1.readLine()); // and here
}
You are skipping a line each time you loop...
Do,
String line=null;
while((line=reader1.readLine())!= null) // reading here
{
System.out.println(line); // and displaying here
}
Consider using Scanner which thanks to hasNextLine() method makes iterating more intuitive.
Scanner scanner = new Scanner(reader1);
while (scanner.hasNextLine() ) {//check if next line exists
System.out.println(scanner.nextLine());//use this next line
}
scanner.close();
I prefer this idiom
for (String curLine; (curLine=reader1.readLine()) != null;) {
System.out.println(curLine);
}
it's good because curLine var is needed only inside loop
Change this in your code.
String curLine = "";
while((curLine=reader1.readLine())!= null)
{
System.out.println(curLine);
}
reader1.readLine() will read your line in while loop and again inside while loop which create problem in not displaying whole XML file.
Change the while loop.
String line;
while( (line=reader1.readLine() ) != null)
{
System.out.println(line);
}
Im trying to read a simple text file with contents
input.txt
Line 1
Line 2
Line 3
But it always goes to the exception and prints Error.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR");
}
}
}
Im using Eclipse as my IDE if that makes a difference. I've tried this code on http://www.compileonline.com/compile_java_online.php
and it runs fine, why wont it run in Eclipse?
give complete file path like "C:\\folder_name\\input.txt" or place input.txt inside src directory of eclipse project.
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(
new FileReader("input.txt")); //<< your problem is probably here,
//More than likely you have to supply a path the input file.
//Something like "C:\\mydir\\input.txt"
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR"); //This tells you nothing.
System.out.println(e.getMessage()); //Do this
//or
e.printStackTrace(); //this or both
}
}
}
You most likely have a bad path. Consider this main instead:
public class Main {
public static void main(String args[]) throws Exception {
List<String> text = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}
}
The "throws Exception" addition allows you to focus on the code, and consider better error handling later. Also consider using File f = new File("input.txt") and use that, because it allows you to print out f.getAbsolutePath() which tells you the filename it was actually looking for.
Changing input.txt to src\\input.txt solved the problem!
I guess it was because the current directory isnt actually the src folder its the parent,
Thanks for the help!
Following to some forums answers I'm using this:
while (fileReader.nextLine() != null) {
String line = fileReader.nextLine();
System.out.println(line);
}
... but it throws exception at the end anyway
(Exception in thread "main" java.util.NoSuchElementException: No line found)
Each call to nextLine() moves onto the next line, so when you are actually at the last readable line and the while check passes inspection, the next call to nextLine() will return EOF.
Perhaps you could do one of the following instead:
If fileReader is of type Scanner:
while ((line = fileReader.hasNextLine()) != null) {
String line = fileReader.nextLine();
System.out.println(line);
}
If fileReader is of type BufferedReader:
String line;
while ((line = fileReader.readLine()) != null) {
System.out.println(line);
}
So you're reading the current line in the while condition and saving the line in a string for later use.
you should use while (fileReader.hasNextLine())
To read a file Scanner class is recommended.
Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
try {
while (scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
}
finally{
scanner.close();
}
The others told you enough about your issue with multiple calls of readLine().
I just wanted to leave sth about code style:
While you see this line = assignement and != null check together in one while condition in most examples (like #gotomanners example here) I prefer using a for for it.
It is much more readable in my opinion ...
for (String line = in.readLine(); line != null; line = in.readLine()) {
...
}
Another nice way to write it you see in #TheCapn's example. But when you write it that way you easily see that's what a for-loop is made for.
I do not like assignments scrambled with conditions in one line. It is bad style in my opinion. But because it is so MUCH popular for that special case here to do it that way I would not consider it really bad style. (But cannot understand who established this bad style to become that popular.)
The problem is that you're reading nextLine() on the while loop and THEN reading it to a variable. Not only are you getting every 2nd line printed out you're opening yourself to the exception being thrown. An example:
File:
Hello,
Blah blah blah,
Sincerely,
CapnStank
PS. Something something
On first iteration through the loop. The check on while will consume the "Hello," as not equal to null. Inside the loop body you'll see Blah blah blah, printed to the System.
The process will repeat with Sincerely, being consumed and Capnstank printing out.
Finally the while will consume the "PS" line while the String line = fileReader.nextLine() retreives an exception from the file because there's nothing further to read.
To resolve the issue:
String line = fileReader.nextLine();
while (line != null) {
System.out.println(line);
line = fileReader.nextLine();
}
nextLine() will throw an exception when there's no line and it will never return null,you can try the Scanner Class instead : http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
while(inFile.hasNext())
This is correct in java programming language
//By: Ishraga Mustafa Awad Allam
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class B_C_Data {
public static void main(String[] args) {
try {
// Create a file reader
FileInputStream fr = new FileInputStream(args[0]);
// Create a file output stream
DataInputStream dr = new DataInputStream(fr);
// Read and display data
while (dr.available() > 0) {
System.out.println(dr.readDouble());
}
// Close file input stream
dr.close();
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}