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 8 years ago.
Improve this question
I need to read lines from an input path (file).
to do so the main calls a class that uses BufferedReader , it iterates over each line and adds it to an Array.
the problem is:
I want to catch all exceptions thrown from the method in the class in the main.
public static void main (String[] args){
if (args.length != 2){
System.err.print("ERROR");
return;
}
MyFileScript.sourceDir = args[SOURCE_DIR_INDEX];
MyFileScript.commandFile = args[COMMAND_INDEX];
try (FileReader file = new FileReader(MyFileScript.commandFile);
BufferedReader reader = new BufferedReader(file)){
fileParsing = new CommandFileParser(reader);
sectionList = fileParsing.parseFile();
}catch (FileNotFoundException error){
System.err.print(ERROR_MESSAGE);
return;
}catch(IOException error){
System.err.print(ERROR_MESSAGE);
return;
}catch(ErrorException error){
System.err.print(error.getMessage());
return;
}
}
public class CommandFileParser {
public CommandFileParser (BufferedReader reader){
this.reader = reader;
}
/**
* read all lines from a file.
*
* #return a string array containing all file lines
*/
public String[] readFileLines(){
ArrayList<String> fileLines = new ArrayList<String>();
String textLine;
while ((textLine = this.reader.readLine()) != null){
fileLines.add(textLine);
}
String[] allFileLines = new String[fileLines.size()];
fileLines.toArray(allFileLines);
return allFileLines;
}
in the while loop I get a compilation error for unhandling the IOException.
How can I catch all exceptions in main,
and so the class takes only one string argument?
your readFileLines method is lacking a throws clause.
public String[] readFileLines() throws IOException {
Related
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 5 years ago.
Improve this question
I have two .txt file (file1.txt and file2.txt). In these file there are some lines of character. My intention is to merge the content of these two file into another file(file3.txt). My code is below:
public static void main(String[] args) {
try {
PrintWriter pw = new PrintWriter("file3.txt");
BufferedReader br1 = new BufferedReader(new FileReader("file1.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("file2.txt"));
String line = br1.readLine();
while(line!=null){
pw.println(line);
br1.readLine();
}
line = br2.readLine();
while (line!=null) {
pw.println(line);
br2.readLine();
}
pw.flush();
pw.close();
br1.close();
br2.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaIoProject.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JavaIoProject.class.getName()).log(Level.SEVERE, null, ex);
}
}
When compile there is no error. After running when i try to see expected output inside (file3.txt) it does not show anything and mouse pointer change to processing. Why this happens. Where is the missing part that i forgot to add or which part should i edit and why.. Need your help.. thanks.
You miss to reassign the value for line in the loop so you get an infinite loop.
Change both while loops:
while (line!=null) {
pw.println(line);
line =br2.readLine();
}
Lots of code you have repeated multiple times in your implementation. You can
simply create a method and invoke it as per filename.
PrintWriter pw = new PrintWriter("file3.txt");
readAndWrite(pw, "file1.txt");
readAndWrite(pw, "file2.txt");
pw.flush();
pw.close();
and this is definition of readAndWrite method. Also correct the loop.
private static void readAndWrite(PrintWriter pw, String filename) throws FileNotFoundException, IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line = br.readLine();
while (line!=null) {
pw.println(line);
line =br.readLine();
}
br.close();
}
You were missing the assignment. So You can try something like this.
String line ="";
while((line=br1.readLine())!=null){
pw.println(line);
}
line = "";
while ((line=br2.readLine())!=null) {
pw.println(line);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to make a stream, so I can read 2 lines from .txt file to two string variables. I tried try/catch, but still have an ureported exception error.
public class Shad1 {
public void myMethod()throws FileNotFoundException {
String stringName = new String("");
String stringNumb = new String("");
File file = new File ("c:\\input.txt");
try {
DataInputStream input = new DataInputStream(new FileInputStream(file));
int check = input.read();
char data = input.readChar();
while(data != '\n') {
stringName = stringName + data;
}
while (check != -1){
stringNumb = stringNumb + data;}
input.close();
} catch (FileNotFoundException fnfe){System.out.println(fnfe.getMessage());}
}
you're using the read method: note that this method can also throw an IOException. See the docs for the read method here, the declaration is:
public final int read(byte[] b) throws IOException
So you'll also need to catch IOException, or report that your method throws IOException.
Note that you don't need to do both, so in your example code, you can similarly choose to report that your method throws FileNotFoundException or declare it in a catch block: you don't need both (unless some other part of the code in the method might generate an unhandled FileNotFoundException).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i have a file named "file" which is a text file(the file contains 1,2,3,4 integers).. Now i want to read this file and split the values in the file and print each value in new line. How can i do that??
Try this:
public static void main( String args[] )
{
try {
Scanner sc = new Scanner(new File("number.txt"));
sc.useDelimiter(",");
while (sc.hasNextInt()) {
System.out.println(sc.nextInt());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public class Main {
public static void main(String[] str) throws Exception{
File f = new File("C:\\prince\\temp\\test.txt");
FileInputStream fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
String[] splitedTokens = line.split("[,]");
for (String splitedToke : splitedTokens) {
System.out.println(splitedToke);
}
}
}
}
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 9 years ago.
Improve this question
I'm working on this java program and I keep getting error from the IsLetterOrDigit method invocation, it's confusing me as I've used isLetter() already in the program and I didn't get any error from that one, somebody help me please.
import java.io.*;
import java.util.*;
import java.lang.*;
public class A11{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(args[0]));
BufferedWriter bw = new BufferedWriter(new FileWriter("A1.output"));
List<String> keywords = Arrays.asList("IF", "ELSE", "WRITE", "READ", "RETURN", "BEGIN", "END", "MAIN", "INT", "REAL");
List<String> l = new LinkedList<String>();
String line, word;
while((line = br.readLine()) != null){
StringTokenizer tk = new StringTokenizer(line, " ;)*,(");
while(tk.hasMoreTokens()){
word = tk.nextToken();
if(!keywords.contains(word)){
if(Character.isLetter(word.charAt(0) )){
for(int i=0; i<word.length(); ++i){
if(Character.IsLetterOrDigit(word.charAt(i))){//Error here
System.out.println(word);
}
}
}
}
}
}
}
}
Remember Java is case-sensitive:
IsLetterOrDigit(...)
must be
isLetterOrDigit(...)
change this
Character.IsLetterOrDigit(word.charAt(i))
to
Character.isLetterOrDigit(word.charAt(i))
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 8 years ago.
Improve this question
I’m trying to create a Java String[] from the content of a file.
The code is:
private String[] arr;
private List<String> list = new ArrayList<String>();
public String[] readfile (String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
while((str = br.readLine()) != null){
list.add(str);
}
arr = list.toArray(new String[list.size()]);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null){
br.close();
}
} catch (IOException e2) {
e2.printStackTrace();
}
}
return arr;
}
The function apparently works. In fact, the variable arr contains the content of file.
However, after this line, arr = list.toArray(new String[list.size()]); the function doesn’t return arr. I get java.lang.StringIndexOutOfBoundsException: String index out of range: 0
What could be the problem?
Finally, the code I had provided was causing the exception. The problem is related to try catch block and variable scope.
Here, arr = list.toArray(new String[list.size()]); the variabe arr contains all lines of file. However, in this line return arr; the content is null;
For that, when I initialize the array and I put a simply return arr in the method, it works. In this case, I don’t have any try catch block.