Note that there are some explanatory texts on larger screens.

plurals
  1. POReading a file in Java
    text
    copied!<p>I have the following code to open and read a file. I'm having trouble figuring out how I can have it go through and print the total number of each character in the file, print the first and last character, and print the character exactly in the middle of the file. What's the most efficient way to do this?</p> <p>This is the main class:</p> <pre><code>import java.io.IOException; public class fileData { public static void main(String[ ] args) throws IOException { String file_name = "/Users/JDB/NetBeansProjects/Program/src/1200.dna"; try { ReadFile file = new ReadFile(file_name); String[] arrayLines = file.OpenFile(); int i; for (i=0; i&lt;arrayLines.length; i++) { System.out.println(arrayLines[i]); } } catch (IOException e) { System.out.println(e.getMessage()) ; } } } </code></pre> <p>and the other class:</p> <pre><code>import java.io.IOException; import java.io.FileReader; import java.io.BufferedReader; public class ReadFile { private String path; public ReadFile (String file_path) { path = file_path; } public String[] OpenFile() throws IOException { FileReader fr = new FileReader(path); BufferedReader textReader = new BufferedReader(fr); int numberOfLines = readLines(); String[] textData = new String[numberOfLines]; int i; for(i=0; i&lt;numberOfLines; i++) { textData[i] = textReader.readLine(); } textReader.close(); return textData; } int readLines() throws IOException { FileReader file_to_read = new FileReader(path); BufferedReader bf = new BufferedReader(file_to_read); String aLine; int numberOfLines = 0; while (( aLine = bf.readLine() ) != null) { numberOfLines++; } bf.close(); return numberOfLines; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload