Reading a file in Java - java

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?
This is the main class:
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<arrayLines.length; i++)
{
System.out.println(arrayLines[i]);
}
}
catch (IOException e) {
System.out.println(e.getMessage()) ;
}
}
}
and the other class:
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<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;
}

Some hints which might help.
A Map can be used to store information about each character in the alphabet.
The middle of the file can be found from the size of the file.

These few lines of code will do it (using Apache's FileUtils library):
import org.apache.commons.io.FileUtils;
public static void main(String[] args) throws IOException {
String str = FileUtils.readFileToString(new File("myfile.txt"));
System.out.println("First: " + str.charAt(0));
System.out.println("Last: " + str.charAt(str.length() - 1));
System.out.println("Middle: " + str.charAt(str.length() / 2));
}
Anyone who says "you can't use libraries for homework" isn't being fair - in the real world we always use libraries in preference to reinventing the wheel.

The easiest way to understand I can think of is to read the entire file in as a String. Then use the methods on the String class to get the first, last, and middle character (character at index str.length()/2).
Since you are already reading in the file a line at a time, you can use a StringBuilder to construct a string out of those lines. Using the resulting String, the charAt() and substring() methods you should be able to get out everything you want.

Related

Is it possible to create fileIO within a program?

I have a bunch of code that has now evolved into a fully functioning console based (mostly) game. I'm now curious that if I want to implement an Input/Output function do I have to create it in a different file or can I put it in the same class as my code. For instance, an example my lecturer has given for writing a fileIO for saving names is the following:
import java.io.*;
class savenames
{
public static void main(String[] params) throws IOException
{
PrintWriter outputStream = new PrintWriter(new FileWriter("mydata.txt"));
// Create an array with some sample names to store
String [] names = {"Paul", "Jo", "Mo"};
// Store the names from the array in the file, one name per line
for (int i = 0; i < names.length; i++)
{
outputStream.println(names[i]);
}
outputStream.close();
System.exit(0);
}
}
This accompanies the following code (in a different file):
import java.io.*;
class readnames
{
public static void main(String[] params) throws IOException
{
BufferedReader inStream = new BufferedReader(new FileReader("mydata.txt"));
String [] names = new String[3];
System.out.println("The names in the file mydata.txt are:");
for (int i = 0; i < names.length; i++)
{
names[i] = inStream.readLine();
System.out.println(names[i]);
}
inStream.close();
System.exit(0);
}
}
I was just wondering if it would be possible do the two things in the same file, as my code has many different methods and I'm not sure how to make a separate method to do this. Thanks.
EDIT: Perhaps I can modify this question to make it a little better.
I have the following main method in my boardgame:
class newminip
{
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
System.exit(0);
}
.... insert code here ....
public static void exitmethod(int[] scorep1)
{
sort(scorep1);
for (int i = 0; i < 4; i++)
{
System.out.println("Player " + (i+1) + " scored " + scorep1[i] + "");
}
System.exit(0);
}
} //END class
And I want something that will save the scores into a new text file. I hope this had made it a tiny bit clearer.
Yes you could do it in one file. I have created a new class for it:
import java.io.*;
import java.util.ArrayList;
public class FileIO {
public static String[] readStringsFromFile(final String filename) throws IOException {
BufferedReader inStream = new BufferedReader(new FileReader(filename));
//Use ArrayList since you don't know how many lines there are in the file
ArrayList<String> lines = new ArrayList<String>();
String line;
//Read until you reach the end of the file
while ((line = inStream.readLine()) != null) {
lines.add(line);
}
inStream.close();
//Convert it back to a string array
return lines.toArray(new String[lines.size()]);
}
public static void writeStringsToFile(String[] lines, final String filename) throws IOException {
PrintWriter outputStream = new PrintWriter(new FileWriter(filename));
for (int i = 0; i < lines.length; i++) {
outputStream.println(lines[i]);
}
outputStream.close();
}
public static void main(String[] args) {
//To test the methods:
//Create an array to write to the file
String[] linesToWrite = {"firstLine", "secondLine", "thirdLine"};
try {
//Write the strings to a file named "testfile.txt"
writeStringsToFile(linesToWrite, "testfile.txt");
//Read all lines of a file named "testfile.txt"
String[] readLines = readStringsFromFile("testfile.txt");
//Print out the read lines
for (String line : readLines) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error msg");
}
}
}
The main method in this case is just to test, you can remove it and copy the two other methods to your class. This is probably not the best or most efficient way to do file io but in your case this should do the job (:
EDIT:
So if you just need to read an write integers to a file you could use something like this:
import java.io.*;
import java.util.ArrayList;
public class FileIO {
public static Integer[] readIntegersFromFile(final String filename) throws IOException {
BufferedReader inStream = new BufferedReader(new FileReader(filename));
//Use ArrayList since you don't know how many lines there are in the file
ArrayList<Integer> integers = new ArrayList<Integer>();
String line;
//Read until you reach the end of the file
while ((line = inStream.readLine()) != null) {
//Parse integers form read string values
integers.add(Integer.parseInt(line));
}
inStream.close();
return integers.toArray(new Integer[integers.size()]);
}
public static void writeIntegersToFile(Integer[] lines, final String filename) throws IOException {
PrintWriter outputStream = new PrintWriter(new FileWriter(filename));
for (int i = 0; i < lines.length; i++) {
outputStream.println(lines[i]);
}
outputStream.close();
}
public static void main(String[] args) {
//To test the methods:
//Create an array to write to the file
Integer[] linesToWrite = {1, 100, 15};
try {
//Write the strings to a file named "testfile.txt"
writeStringsToFile(linesToWrite, "testfile.txt");
//Read all lines of a file named "testfile.txt"
Integer[] readLines = readStringsFromFile("testfile.txt");
//Print out the read lines
for (int line : readLines) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error msg");
}
}
}
You can create a Java file with the code from both main methods and remove the System.exit(0); as you don't need it. This way one program will do both. I suggest you write the file before attempting to read it.
Putting it all in one program make the use of the file rather redundant however, in which case you can just print the array.

Reading character files between specific word in java

I have a java file, FileJava.java like this:
public class FileJava {
public static void main(String args[]) {
for (int i = 0; i < 5; i++) {
}
}
}
Then, i read above code line by line using this code:
import java.util.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
public class FileReplace {
List<String> lines = new ArrayList<String>();
String line = null;
public void doIt() {
try {
File f1 = new File("FileJava.java");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.contains("for"))
{
lines.add("long A=0;");
if(line.contains("(") && line.contains(")")){
String get = line;
String[] split = get.split(";");
String s1 = split[0];
String s2 = split[1];
String s3 = split[2];
}
}
lines.add(line);
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
FileReplace fr = new FileReplace();
fr.doIt();
}
}
The question is, how to read character between '(' and ')' inside (for) in the FileJava.java, the character i mean "int i = 0; i < 5; i++" that will be stored in a variable, i have split based on ";", but when i print, the value :
s1 = for (int i = 0
s2 = i < 5
s3 = i++) {
While i expect:
s1 = int i = 0
s2 = i < 5
s3 = i++
Thanks
To answer your question how to restrict the splitting to the parenthesized section:
String[] split =
get.substring( get.indexOf('(')+1, get.indexOf(')').split("\\s*;\\s*");
Edit to address another prob.
Printing of the file will all happen in one line, because BufferedReader.readLine strips the line ends (LF, CRLF) from the line it returns. Thus, add a line break when writing:
for(String s : lines){
out.write(s);
out.newLine();
}
int index1 = line.indexOf("(");
int index2 = line.indexOf(")");
line = line.subString(index1 + 1, index2);
Its because you are splitting on ';' for the input
for (int i = 0; i < 5; i++) {
which will return all the characters between ';'
You can write a new method, called getBracketContent for example, that will be something like
String getBracketContent(String str)
{
int startIdx = str.indexOf('(')
int endIdx = str.indexOf(')')
String content = str.subString(startIdx + 1, endIdx);
}
then your code would be
if(line.contains("(") && line.contains(")")){
String get = getBracketContent(line);
String[] split = get.split(";");
Ideally I would use regular expressions to parse the information you need, but that is probably something you may want to look into later.
If you want to read the contents of a java file, you would be much better off using an AST (Abstract Syntax Tree) parser which will read in the contents of the file and then callback when it encounters certain expressions. In your case, you can listen just for the 'for' loop.

Code for reading from a text file doesn't work

I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.
I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.
I have altered it a bit from what I was given. Here is where I am now:
This is my main class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/Users/Desktop/test.txt";
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int nLines = file.readLines();
int i = 0;
for (i = 0; i < nLines; i++) {
System.out.println(aryLines[i]);
}
}
}
This is my class that will read the text file and sense the number of lines
package textfiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
int numberOfLines = 0;
String aLine;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.
The problem is, you set the number of lines to read as zero with int numberOfLines = 0;
I'd rather suggest to use a list for the lines, and then convert it to an array.
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = 0; //this is not needed
List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file
//this part should work akin to the readLines part
String aLine;
while ((aLine = bf.readLine()) != null) {
textData.add(aLine); //add the line to the list
}
textReader.close();
return textData.toArray(new String[textData.size()]); //convert it to an array, and return
}
}
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
textData is an empty array. The following for loop wont do anything.
Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
I also suggest that you read tutorials on object oriented concepts.
This is a class that I wrote awhile back that I think you may find helpful.
public class FileIO {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
input.close();
}
} catch (IOException ex) {
}
return contents.toString();
}
static public File OpenFile()
{
return (FileIO.FileDialog("Open"));
}
static private File FileDialog(String buttonText)
{
String defaultDirectory = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(defaultDirectory);
jfc.setMultiSelectionEnabled(false);
jfc.setApproveButtonText(buttonText);
if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION)
{
return (null);
}
File file = jfc.getSelectedFile();
return (file);
}
}
It is used:
File file = FileIO.OpenFile();
It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.

How to tokenize an input file in java

i'm doing tokenizing a text file in java. I want to read an input file, tokenize it and write a certain character that has been tokenized into an output file. This is what i've done so far:
package org.apache.lucene.analysis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
class StringProcessing {
// Create BufferedReader class instance
public static void main(String[] args) throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyboardInput = new BufferedReader(input);
System.out.print("Please enter a java file name: ");
String filename = keyboardInput.readLine();
if (!filename.endsWith(".DAT")) {
System.out.println("This is not a DAT file.");
System.exit(0);
}
File File = new File(filename);
if (File.exists()) {
FileReader file = new FileReader(filename);
StreamTokenizer streamTokenizer = new StreamTokenizer(file);
int i = 0;
int numberOfTokensGenerated = 0;
while (i != StreamTokenizer.TT_EOF) {
i = streamTokenizer.nextToken();
numberOfTokensGenerated++;
}
// Output number of characters in the line
System.out.println("Number of tokens = " + numberOfTokensGenerated);
// Output tokens
for (int counter = 0; counter < numberOfTokensGenerated; counter++) {
char character = file.toString().charAt(counter);
if (character == ' ') { System.out.println(); } else { System.out.print(character); }
}
} else {
System.out.println("File does not exist!");
System.exit(0);
}
System.out.println("\n");
}//end main
}//end class
When i run this code, this is what i get:
Please enter a java file name: D://eclipse-java-helios-SR1-win32/LexractData.DAT
Number of tokens = 129
java.io.FileReader#19821fException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 25
at java.lang.String.charAt(Unknown Source)
at org.apache.lucene.analysis.StringProcessing.main(StringProcessing.java:40)
The input file will look like this:
-K1 Account
--Op1 withdraw
---Param1 an
----Type Int
---Param2 amount
----Type Int
--Op2 deposit
---Param1 an
----Type Int
---Param2 Amount
----Type Int
--CA1 acNo
---Type Int
-K2 CheckAccount
--SC Account
--CA1 credit_limit
---Type Int
-K3 Customer
--CA1 name
---Type String
-K4 Transaction
--CA1 date
---Type Date
--CA2 time
---Type Time
-K5 CheckBook
-K6 Check
-K7 BalanceAccount
--SC Account
I just want to read the string which are starts with -K1, -K2, -K3, and so on... can anyone help me?
The problem is with this line --
char character = file.toString().charAt(counter);
file is a reference to a FileReader that does not implement toString() .. it calls Object.toString() which prints a reference around 25 characters long. Thats why your exception says OutofBoundsException at the 26th character.
To read the file correctly, you should wrap your filereader with a bufferedreader and then put each readline into a stringbuffer.
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null) {
sb.append(s);
}
// Now use sb.toString() instead of file.toString()
If you are wanting to tokenize the input file then the obvious choice is to use a Scanner. The Scanner class reads a given input stream, and can output either tokens or other scanned types (scanner.nextInt(), scanner.nextLine(), etc).
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("filename.dat"));
while (in.hasNext) {
String s = in.next(); //get the next token in the file
// Now s contains a token from the file
}
}
Check out Oracle's documentation of the Scanner class for more info.
public class FileTokenize {
public static void main(String[] args) throws IOException {
final var lines = Files.readAllLines(Path.of("myfile.txt"));
FileWriter writer = new FileWriter( "output.txt");
String data = " ";
for (int i = 0; i < lines.size(); i++) {
data = lines.get(i);
StringTokenizer token = new StringTokenizer(data);
while (token.hasMoreElements()) {
writer.write(token.nextToken() + "\n");
}
}
writer.close();
}

Java file read problem

I have a java problem. I am trying to read a txt file which has a variable number of integers per line, and for each line I need to sum every second integer! I am using scanner to read integers, but can't work out when a line is done. Can anyone help pls?
have a look at the BufferedReader class for reading a textfile and at the StringTokenizer class for splitting each line into strings.
String input;
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
while ((input = br.readLine()) != null) {
input = input.trim();
StringTokenizer str = new StringTokenizer(input);
String text = str.nextToken(); //get your integers from this string
}
If I were you, I'd probably use FileUtils class from Apache Commons IO. The method readLines(File file) returns a List of Strings, one for each line. Then you can simply handle one line at a time.
Something like this:
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
// handle one line
}
(Unfortunately Commons IO doesn't support generics, so the there would be an unchecked assignment warning when assigning to List<String>. To remedy that use either #SuppressWarnings, or just an untyped List and casting to Strings.)
This is, perhaps, an example of a situation where one can apply "know and use the libraries" and skip writing some lower-level boilerplate code altogether.
or scrape from commons the essentials to both learn good technique and skip the jar:
import java.io.*;
import java.util.*;
class Test
{
public static void main(final String[] args)
{
File file = new File("Test.java");
BufferedReader buffreader = null;
String line = "";
ArrayList<String> list = new ArrayList<String>();
try
{
buffreader = new BufferedReader( new FileReader(file) );
line = buffreader.readLine();
while (line != null)
{
line = buffreader.readLine();
//do something with line or:
list.add(line);
}
} catch (IOException ioe)
{
// ignore
} finally
{
try
{
if (buffreader != null)
{
buffreader.close();
}
} catch (IOException ioe)
{
// ignore
}
}
//do something with list
for (String text : list)
{
// handle one line
System.out.println(text);
}
}
}
This is the solution that I would use.
import java.util.ArrayList;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) throws IOException{
String nameFile;
File file;
Scanner keyboard = new Scanner(System.in);
int total = 0;
System.out.println("What is the name of the file");
nameFile = keyboard.nextLine();
file = new File(nameFile);
if(!file.exists()){
System.out.println("File does not exit");
System.exit(0);
}
Scanner reader = new Scanner(file);
while(reader.hasNext()){
String fileData = reader.nextLine();
for(int i = 0; i < fileData.length(); i++){
if(Character.isDigit(fileData.charAt(i))){
total = total + Integer.parseInt(fileData.charAt(i)+"");
}
}
System.out.println(total + " \n");
}
}
}

Categories

Resources