Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to write a code for selecting features from a txt file.
i.e. size = 1.4356474
species = fw, wevb, wrg , gwe
....
this is the code I wrote so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.concurrent.ExecutionException;
public class Metodi {
public static void main (String[] args) {
String volume = findVolume();
System.out.println(volume);
}
public static String readSpecification() {
String spec = "";
// trying to read from file the specification...
try {
BufferedReader reader = new BufferedReader(new FileReader("Gemcitabine.txt"));
String line = reader.readLine();
while(line!=null) {
spec += line + "\n";
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return spec;
}
public static String findVolume () {
String res = "";
String vol = "volume";
try {
BufferedReader reader1 = new BufferedReader(new FileReader("Sample.txt"));
String line1 = reader1.readLine();
while(line1!=null) {
if(line1.toLowerCase().indexOf(vol) != -1) {
String[] str = line1.split("=");
res = str[1].split(" ")[0];
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return res;
}
}
It doesn't give me any compiler's error, but when I launch it, it keeps running and doesn't end.
Any help?
Your loop is not reading line after line, it needs to call read line on each iteration, it should be :
String line1 =;
while((line1 = reader1.readLine()) != null) {
if(line1.toLowerCase().indexOf(vol) != -1) {
String[] str = line1.split("=");
res = str[1].split(" ")[0];
}
}
In findVolume(), you check line1 != null in your while-condition.
You never change line1 within the loop. Thus, it will never be equal to null and the loop won't terminate.
Related
I have a file of multiple lines saved on my computer. In my java program, I am trying to ask the user to enter a string of letters or a word, and then have the program print out the lines only where that string of letters or word is. I know I have to import the scanner class, but how do I print out these user-specified lines?
Also, these lines of text are numbered (1-20). How do I print out just the text characters and ignore the integers when reprinting the original code? For example, one line of the code is "1. example of the first line of code"
Below is my code I have so far:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader("/Users/wolftrek/Downloads/example.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
myFileLines.add(sCurrentLine);
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
for (int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains("example word")) {
System.out.println(myFileLines.get(i));
}
}
}
}
Suppose that file.txt only contains "Hello". When I compile the Java code, it shows
Error: This method must return a result of type java.lang.String in line5.
When I print in readTxt function, that works, it can show "Hello".
I already check the result is correctly String type, but it also shows compiler error. How can I make the return value to the main function?
import java.io.*;
import java.lang.String;
public class ReadTxtFile {
public static String readTxt(String filePath) {
try {
File file = new File(filePath);
if(file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null;
lineTxt = br.readLine();
//System.out.println(lineTxt);
br.close();
return lineTxt;
} else {
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
String filePath = "C:/file.txt";
String fileword = readTxt(filePath);
System.out.println(fileword);
}
}
You promised to return a String from your method, so you now have to do that. The only way around that promise is to throw an exception.
public static String readTxt(String filePath) { // Here you promise to return a String
try {
...
if(file.isFile() && file.exists()) {
...
return lineTxt; // Here you return a String as promised
} else {
// Here you're missing either return or throw
}
} catch (Exception e) {
// Here you're missing either return or throw
}
}
This is fundamentally a design problem - what should your method do if it fails to read the file for some reason? Return a special string like "Error"? Return null? Fail and throw and exception? Something else?
Answer that to yourself and it will be clear to you how to fix the code.
There are several best practices you should follow that will prevent future error. I have tried to cover them. Not saying mine is the perfect one, but you will get the idea.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class StackOverFlow {
public static void main(String[] args) {
try {
String sText = getFileText("C:/file.txt");
System.out.println("Text is: " + sText);
} catch (FileNotFoundException e) {
System.out.println("File not Found");
} catch (IOException e) {
System.out.println("#Error while reading text: " + e.getMessage());
}
}
private static String getFileText(String filePath) throws FileNotFoundException, IOException {
File file = new File(filePath);
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
}finally {
reader.close();
}
return new String(stringBuilder);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hi I am getting this error on my Java code
Syntax error on token "(", ; expected
I am trying to make a function, maybe my syntax is not correct.
this is my code:(I point where the error is)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
String ruta = "C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt";
File archivo = new File(ruta);
String linea = null;
try {
FileReader lector = new FileReader(archivo);
BufferedReader buff = new BufferedReader(lector);
while( ( linea = buff.readLine() ) != null ) {
System.out.println(linea);
}
buff.close();
lector.close();
} catch(FileNotFoundException ex) {
} catch(IOException ex) {
}
final int countWord(String codigo, File archivo)<-------Error Here
{
int count = 0;
Scanner scanner = new Scanner("C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(codigo))
count++;
}
return count;
}
}
}
Sorry if it is something really simple, this is all in my main class.
Move the } from the bottom of your code to the end of the main method.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
String ruta = "C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt";
File archivo = new File(ruta);
String linea = null;
try {
FileReader lector = new FileReader(archivo);
BufferedReader buff = new BufferedReader(lector);
while( ( linea = buff.readLine() ) != null ) {
System.out.println(linea);
}
buff.close();
lector.close();
} catch(FileNotFoundException ex) {
} catch(IOException ex) {
}
}
final int countWord(String codigo, File archivo){
int count = 0;
Scanner scanner = new Scanner("C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(codigo))
count++;
}
return count;
}
}
You're missing a closing brace on your main method, just before the line that's giving you the error message. Unfortunately, sometimes syntax errors that are not obvious at the point they occur end up making something later appear wrong, and so the compiler's error message can be misleading.
What can help is using a good editor that understands the language. You might already be doing that. If so, the fact that your editor placed the first line of your countWord definition at the same level as your main method body is a hint that you didn't properly close out the latter.
I re-formated your code, so the error gets more obvious
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HelloWorld {
public static void main(String... args) {
String ruta = "C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt";
File archivo = new File(ruta);
String linea = null;
try {
FileReader lector = new FileReader(archivo);
BufferedReader buff = new BufferedReader(lector);
while ((linea = buff.readLine()) != null) {
System.out.println(linea);
}
buff.close();
lector.close();
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
} // Moved this parenthesis up
final int countWord(String codigo, File archivo) { // <-------Error Here
int count = 0;
Scanner scanner
= new Scanner("C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(codigo)) {
count++;
}
}
return (count);
}
}
Some remarks on your code:
you should take a look at the try-with-resources.
you should definitely write your code with english variable-/attribute names
even if you can neglect some parenthesis (i.e. ifs with only a single line of code), you should write them for clarity
I'm trying to read a file in java. In that file, some string is given which I want to print. But my code prints only lines of even numbers and skips lines of odd numbers.
I searched for that in stackoverflow, but have found no solution previously answered.
My code is given below...
//main class
import java.io.IOException;
public class takingInputFrpmFile {
public static void main(String[] args) throws IOException {
String filePath = "F:/Path/in.txt";
try
{
readFile rF = new readFile(filePath);
String[] receivedArray = rF.Read();
for(int i=0;i<receivedArray.length;i++)
System.out.println(receivedArray[i]);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
// class called from main class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class readFile {
private String path;
public readFile(String path)
{
this.path=path;
}
public String[] Read() throws IOException
{
FileReader fR = new FileReader(path);
BufferedReader bR = new BufferedReader(fR);
String[] textData = new String[110];
String check;
int i=0;
while((check = bR.readLine()) != null)
{
textData[i] = bR.readLine();
i++;
}
bR.close();
return textData;
}
}
The file contains this lines...
This is the output of my code....
What is wrong with my code? What should I change? How to get rid of printing that last nulls ? Help please... Thanks in advance...
You are first reading the line and checking it's not null, then you read another line.
while((check = bR.readLine()) != null)
{
textData[i] = check; //Changed this to check
i++;
}
That one will work.
You are currently declaring String array which has size of 110. Is your file really 110 line long? You probably should use list instead.
public List<String> Read() throws IOException
{
FileReader fR = new FileReader(path);
BufferedReader bR = new BufferedReader(fR);
List<String> textData = new ArrayList<>();
String check;
while((check = bR.readLine()) != null)
{
textData.add(check);
}
bR.close();
return textData;
}
If you really want to return string array you can use:
return textData.toArray(new String[textData.size()]);
You are reading file lines twice, one when you do
check = bR.readLine()
and other when you do
textData[i] = bR.readLine();
(Each bR.readLine() reads one line)
Try changing your loop for something like
while ((textData[i] = bR.readLine()) != null) {
i++;
}
To get rid of the nulls, you can use a List instead of using a fixed size (110) array.
I suggest the following code:
//main class
import java.io.IOException;
import java.util.List;
public class Prueba {
public static void main(String[] args) throws IOException {
String filePath = "E:/Temp/in.txt";
try {
ReadFile rF = new ReadFile(filePath);
List<String> receivedArray = rF.read();
for (String currentLine : receivedArray) {
System.out.println(currentLine);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
//class called from main class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
private final String path;
public ReadFile(String path) {
this.path = path;
}
public List<String> read() throws IOException {
// Create an empty List to protect against NPE
List<String> textData = new ArrayList<String>();
FileReader fR = null;
BufferedReader bR = null;
try {
fR = new FileReader(path);
bR = new BufferedReader(fR);
String line;
while ((line = bR.readLine()) != null) {
textData.add(line);
}
} catch (IOException e) {
throw e;
} finally {
// Close all the open resources
bR.close();
fR.close();
}
return textData;
}
}
Anyway, as Mukit Chowdhury suggested, please respect code conventions to make your code more readable (you can Google "Java code conventions" or use a well stablished ones)
It seems you do 2 read statements. Try something like:
while((check = bR.readLine()) != null)
{
textData[i] = check;
i++;
}
your line pointer incrementing two times,
while((check = bR.readLine()) != null){
textData[i] = bR.readLine();
i++;
}
Replace bR.readLine() to check in your while loop.
while((check = bR.readLine()) != null){
textData[i] = check ;
i++;
}
You call readline twice. Your loop should read
for(; (check = br.readline()) != null; textdata[i++] = check);
Or something to that effect
In Java 8, reading all lines from a File into a List<String> is easily done using utility classes from the java.nio.file package:
try {
List<String> lines = Files.readAllLines(Paths.get("/path/to/file"));
} catch (IOException e) {
// handle error
}
It's really no longer necessary to use external libraries or to re-invent the wheel for such a common task :)
From your code sample
here
while((check = bR.readLine()) != null) {
textData[i] = bR.readLine();
i++;
}
replace it with
while((check = bR.readLine()) != null) {
textData[i] = check ;
i++;
}
I would like to run a Dos program from a web server. The Dos program has to be run interactively as the user interface is via a series of questions and answers. The answer to one question will determine the next question. I will have to use ajax on the web server, but I think I can do that.
I found one java program on Stackoverflow which seems to do something similar to what I want. However when I compile the program I get an error ie.
javac PipeRedirection.java
PipeRedirection.java:43: package InputProcess does not exist
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
The stack overflow question url was
How can I write large output to Process getOutputStream?
The Java file was
/*
####### PipeRedirection.java
*/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class PipeRedirection {
public static void main(String[] args) throws FileNotFoundException {
if(args.length < 2) {
System.err.println("Need at least two arguments");
System.exit(1);
}
try {
String input = null;
for(int i = 0; i < args.length; i++) {
String[] commandList = args[i].split(" ");
ProcessBuilder pb = new ProcessBuilder(commandList);
//pb.redirectErrorStream(true);
Process p = pb.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
InputProcess.Gobbler errGobbler = new InputProcess.Gobbler(p.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = p.waitFor();
System.out.println("\n****************************");
System.out.println("Command: " + args[i]);
System.out.println("Exit Value = " + exitVal);
List<String> output = outGobbler.getOuput();
input = "";
for(String o: output) {
input += o;
}
}
System.out.println("Final Output:");
System.out.println(input);
} catch (IOException ioe) {
// TODO Auto-generated catch block
System.err.println(ioe.getLocalizedMessage());
ioe.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.err.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public static class Gobbler implements Runnable {
private BufferedReader reader;
private List<String> output;
public Gobbler(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
public void run() {
String line;
this.output = new ArrayList<String>();
try {
while((line = this.reader.readLine()) != null) {
this.output.add(line + "\n");
}
this.reader.close();
}
catch (IOException e) {
// TODO
System.err.println("ERROR: " + e.getMessage());
}
}
public List<String> getOuput() {
return this.output;
}
}
}
Does anyone know why I get the compile error? Can I substitute some other code for InputProcess?
Thanks for any help
Peter
I think it's pretty obvious that you're missing parts to this code. A package named InputProcess which has a class called Gobbler was not included in the OP's post. Probably because it was not relevant to their question.
The error message essentially says that it can not find this package/code that it is looking for.
What this class does exactly, only the OP can tell you. At its most basic, though, it appears to read from an InputStream and convert it to a List<String>. I would read up on Java IO and try to replicate similar functionality.
Edit:
Looks like the Gobbler class is indeed included in the example above. Remove the InputProcess package name from your code (or put the Gobbler class in an InputProcess package) and you should be good to go.