Troubles reading a single character from a text file - java

I'm writing an "app" that takes in time input from the user and stores the hours and the minutes separately for each day in a text file (giving a result that looks like:
day 1: 8h 45min
day 2: 8h 43min
... )
the idea behind it is to use this data for multiple stuff, like calculating the average time, or just accessing the time at any day, but I haven't reached that stage yet, I'm having troubles doing the simplest stuff like reading the hour and printing it.
here's the code
import java.util.Scanner;
import java.io.*;
public class TimeInput {
public static void main(String[] args) {
write();
read();
}
static void write() {
int dayOfMonth = 1;
String fileName = "time.txt";
int[] time = new int[2];
String timeDisplay;
Scanner s = new Scanner(System.in);
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
while (dayOfMonth <=31) {
System.out.println("Day " + dayOfMonth);
System.out.print("Enter hour: " + "__" + "h\r");
System.out.print("Enter hour: ");
time[0] = s.nextInt();
System.out.print("Enter minutes: " + "__" + "min\r");
System.out.print("Enter minutes: ");
time[1] = s.nextInt();
timeDisplay = ("\n"+ "day " + dayOfMonth + ": " + time[0] + "h " + time[1] + "min");
bufferedWriter.write(timeDisplay);
bufferedWriter.newLine();
dayOfMonth++;
if (time[0] == 0 && time[1] == 0) {
bufferedWriter.close();
dayOfMonth = 32; // break
}
}
}
catch (IOException ex) {
System.out.println(
"Error writing to file '" + fileName + "'");
}
}
static void read() {
String fileName = "time.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
char h = line.charAt(7);
System.out.println(h);
}
bufferedReader.close();
}
catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" + fileName + "'" );
}
catch (IOException ex) {
System.out.println(
"Error reading file '" + fileName +"'");
}
}
}
I keep getting a String out of bounds exception and I don't understand why

You need to check empty string before char operation.
while ((line = bufferedReader.readLine()) != null) {
if("".equals(line)){
continue;
}
char h = line.charAt(7);
System.out.println(h);
}

Buffered Writer also saved enter key presses between your input. So to eliminate that enter presses add dummy readLine statement between each line read.
line=bufferedReader.readLine();
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
char h = line.charAt(7);
System.out.println(h);
line=bufferedReader.readLine();
}

Take a look to the last loop.
Put a breakpoint and see what happen. Maybe the ArrayIndexOutBoundExceptions happens cuz youre trying to read more that one character and this cant be possible. Take a look to this url to see how to read a txt with bufferedReader.
http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Hope this help.

Related

Filtering specific team from text file and displaying results

I want my program to allow a user to enter a team name and based on that name it will distribute the pertinent team information to the console for viewing. So far, the program allows the user to input a text file that contains unformatted team data. It then formats that data, stores it and prints the information to the console. It is at this point in my program where I want the user to be able to start her/his filtering based on a team name. I am not necessarily looking for an exact answer but some helpful tips or suggestions would be appreciated.
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
System.out.println();
Scanner fileReader = null;
//A list to add results to, so they can be printed out after the parsing has been completed.
ArrayList<LineResult> results = new ArrayList<>();
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
while(fileReader.hasNext()) {
String line = fileReader.nextLine();// Read a line of data from text file
// this if statement helps to skip empty lines
if ("".equals(line)) {
continue;
}
String [] splitArray = line.split(":");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
//This section checks if each line has any corrupted data
//and then display message to the user.
if("".equals(splitArray[0]))
{
System.out.println(line + " > The home or away team may be missing");
System.out.println();
}else if ("".equals(splitArray[1])) {
System.out.println(line + " > The home or away team may be missing");
System.out.println();
}
try {
// Extract each item into an appropriate variable
LineResult result = new LineResult();
result.homeTeam = splitArray[0];
result.awayTeam = splitArray[1];
result.homeScore = Integer.parseInt(splitArray[2]);
result.awayScore = Integer.parseInt(splitArray[3]);
results.add(result);
} catch(NumberFormatException e) {
System.out.println(line + " > Home team score may not be a valid integer number ");
System.out.println(" or it may be missing");
System.out.println();
}
}else {
System.out.println(line + " > The field delimiter may be missing or ");
System.out.println(" wrong field delimiter is used");
System.out.println();
}
}
System.out.println();
System.out.println();
//Print out results
System.out.println("Home team Score Away team Score");
System.out.println("========= ===== ========= =====");
//Loop through each result printing out the required values.
//TODO: REQ4, filter results based on user requested team
try (BufferedReader br = new BufferedReader(new File(filename));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
if (values.length >= 3)
bw.write(values[0] + ' ' + values[1] + ' ' + values[2] + '\n');
}
}
for (LineResult result : results) {
System.out.println(
String.format("%-15s %1s %-15s %1s",
result.homeTeam,
result.homeScore,
result.awayTeam,
result.awayScore));
}
// end of try block
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
System.out.println();
}
}
//Data object for holding a line result
static class LineResult {
String homeTeam, awayTeam;
int homeScore, awayScore;}
}

PrintWriter & File in java

I wrote a program that will allow the user to store several memos in a file. I figured out how to use PrintWriter & File within Java but my issue is with my output. I can only enter one memo without issue & when I check the file on Notepad, only one memo is present. Here's the code:
import java.util.*;
import java.io.*;
public class MemoPadCreator{
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
boolean lab25 = false;
File file = new File("revisedLab25.txt");
PrintWriter pw = new PrintWriter (file);
String answer = "";
do{
while(!lab25){
System.out.print("Enter the topic: ");
String topic = input.nextLine();
Date date = new Date();
String todayDate = date.toString();
System.out.print("Message: ");
String memo = input.nextLine();
pw.println(todayDate + "\n" + topic + "\n" + memo);
pw.close();
System.out.print("Do you want to continue(Y/N)?: ");
answer = input.next();
}
}while(answer.equals("Y") || answer.equals("y"));
if(answer.equals("N") || answer.equals("n")){
System.exit(0);
}
}
}
Here's the output:
Enter the topic: I love food!
Message: Food is life!
Do you want to continue(Y/N)?: Y
Enter the topic: Message:
How do I go about changing it so the output will allow me to continue storing memos until I tell it to stop?
try {
Files.write(Paths.get("revisedLab25.txt"), ("the text"todayDate + "\n" + topic + "\n" + memo).getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling
}
Because you are looping with potentially multiple writes as the user adds input, you can wrap the writes in a Try-with-resources try block. The try-with-resources takes care of closing the file upon leaving the try block:
try(PrintWriter pw= new PrintWriter(new BufferedWriter(new FileWriter("revisedLab25.txt", true)))) {
do{
while(!lab25){
System.out.print("Enter the topic: ");
String topic = input.nextLine();
Date date = new Date();
String todayDate = date.toString();
System.out.print("Message: ");
String memo = input.nextLine();
pw.println(todayDate + "\n" + topic + "\n" + memo);
System.out.print("Do you want to continue(Y/N)?: ");
answer = input.next();
}
}while(answer.equals("Y") || answer.equals("y"));
}
catch (IOException e) {
//exception handling
}

Scanner adding blank lines with scanning in from a file

I am trying to read in from a file using a Scanner then append these to an Array. However when I do so the Scanner seems to be picking up blank lines and assigning these blanks lines to indexes in the array.
I've tried a fair few different ways of working to no avail and was just wondering if any came along the same problem and new why it would be doing this?
The format of the file is as follows:
F:\Data\SFW3\FOLDER
F:\Data\SFW3\FOLDER
F:\Data\SFW3\FOLDER
F:\Data\SFW3\FOLDER
Any ideas would be greatly welcomed.
public void scanFiles() throws NoSuchElementException {
Scanner sc = null;
System.out.println("Sage 2015 is Installed on this machine");
int i = 0;
try {
String line;
File companyFile = new File(sageFolders[8] + "\\COMPANY");
sc = new Scanner(new BufferedReader(new FileReader(companyFile)));
while(sc.hasNextLine()) {
line = sc.nextLine();
System.out.println(line);
System.out.println(i);
currentFolders.add(i,line);
System.out.println("At Index" + i + ": " + currentFolders.get(i));
i++;
}
sc.close();
}
catch(FileNotFoundException e) {
System.out.println("File not Found: Moving onto next Version");
}
catch(IOException e) {
System.out.println("IO Error");
}
}
Use String.trim().length() to find out if it is a blank line and if not do not add it
System.out.println(i);
if (String.trim().length() > 0) {
currentFolders.add(i,line);
System.out.println("At Index" + i + ": " + currentFolders.get(i));
}
i++;
To achieve your task, try below code:
while(sc.hasNextLine())
{
line = sc.nextLine();
if(null != line && line.trim().length() > 0){
System.out.println(line);
System.out.println(i);
currentFolders.add(i,line);
System.out.println("At Index" + i + ": " + currentFolders.get(i));
i++;
}
}

Read specific data from a .txt file JAVA

I have a problem. I'm trying to read a large .txt file, but I don't need every piece of data that's inside.
My .txt file looks something like this:
8000000 abcdefg hijklmn word word letter
I only need, let's say, the number and the first two text positions: "abcdefg" and "hijklmn" and write it to another file after that. I don't know how to read and write just the data that I need.
Here is my code so far:
BufferedReader br = new BufferedReader(new FileReader("position2.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("position.txt"));
String line;
while ((line = br.readLine())!= null){
if(line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")){
continue;
}else{
//bw.write(line + "\n");
String[] data = line.split(" ");
bw.write(data[0] + " " + data[1] + " " + data[2] + "\n");
}
}
br.close();
bw.close();
}
Can you give me some sugestions ?
Thanks in advance
UPDATE:
My .txt files are a bit weird. Using the code above works great when there is only one single " " between them. My files can have a \t or more spaces, or a \t and some spaces between the words. Ho can I proceed now ?
Depending on the complexity of you data, you have a few options.
If the lines are simple space-separated values like shown, the simplest is to split the text, and write the values you want to keep to the new file:
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
if (values.length >= 3)
bw.write(values[0] + ' ' + values[1] + ' ' + values[2] + '\n');
}
}
If the values might be more complex, you could use a regular expression:
Pattern p = Pattern.compile("^(\\d+ \\w+ \\w+)");
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Matcher m = p.matcher(line);
if (m.find())
bw.write(m.group(1) + '\n');
}
}
This ensures that first value is digits only, and second and third values are word-characters only (a-z A-Z _ 0-9).
Assuming all lines of your text file follow the structure you described then you could do this:
Replace FILE_PATH with your actual file path.
public static void main(String[] args) {
try {
Scanner reader = new Scanner(new File("FILE_PATH/myfile.txt"));
PrintWriter writer = new PrintWriter(new File("FILE_PATH/myfile2.txt"));
while (reader.hasNextLine()) {
String line = reader.nextLine();
String[] tokens = line.split(" ");
writer.println(tokens[0] + ", " + tokens[1] + ", " + tokens[2]);
}
writer.close();
reader.close();
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
You'll get something like:
word0, word1, word2
If your files are really huge (above 50-100 MB maybe GBs) and you are sure that the first word is a number and you need two words after that I would suggest you to read one line and iterate through that string. Stop when you find 3rd space.
String str = readLine();
int num_spaces = 0, cnt = 0;
String arr[] = new String[3];
while(num_spaces < 3){
if(str.charAt(cnt) == ' '){
num_space++;
}
else{
arr[num_space] += str.charAt(cnt);
}
}
If your data is couple of MB only or have a lot of numbers inside, no need to worry about iterating char by char. Just read line by line and split lines then check the words as it is mentioned
else {
String[] res = line.split(" ");
bw.write(res[0] + " " + res[1] + " " + res[2] + "\n"); // the first three words...
}

Output is not coming out correctly

The goal of this code is to read a file and add numbers to the end of every {(curly bracket) but the file does not output each line like it does in the file but it out puts it into one entire line. where do I put a System.out.println statement. I tried every where and it keeps repeating it
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = " ";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count + " ";
} else if (ch == '}') {
out = out + " " + count + " ";
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
where do I put a System.out.println statement
The entire output is built in a single string that is not printed until the end, so adding System.out.println statements in the line loop won't help. You can add line breaks to the string by doing:
out += "\n";
Or, at the end of the body of your line loop, print the current line, and reset the buffer for the next line:
System.out.println(out);
out = "";
Using a String for the output buffer is not efficient by the way. String is immutable, so every + statement is copying and duplicating all of the previous characters to create a new object, every time. Consider declaring out as a StringBuilder rather than a String. Then you can add to it with the .append() method and it will not copy all the text every time because a StringBuilder is mutable.

Categories

Resources