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++;
}
}
Related
output file is created but numbers are not written.
public static void main(String[] args)
{
String file_name;
String done_string = "done";
boolean done = false;
while (!done)
{
file_name = JOptionPane.showInputDialog("Enter a file name" + " or done to exit: ");
if (file_name.equals(done_string))
{
done = true;
JOptionPane.showMessageDialog(null, "EXITING");
}
else
{
try
{
File file_in = new File(file_name);
Scanner input = new Scanner(file_in);
JOptionPane.showMessageDialog(null, "File " + file_name + " found ");
int[] hold_ints = new int[100];
for (int i = 0; i< 100; i++)
{
hold_ints[i] = input.nextInt();
}
PrintWriter output = new PrintWriter("reverse_ints");
for (int i = 99; i <= 0; i--)
{
output.print(hold_ints[i]);
output.print(" ");
}
output.close();
input.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "File " + file_name + " not found ");
}
}
}
}
}
Program should read a file then create an output file that prints the numbers in the input file in reverse.
Actual results just shows the file but nothing is written in the file.
For-loop condition is wrong, so code in the loop is not run.
I suppose it should be
for (int i = 99; i >= 0; i--)
{
output.print(hold_ints[i]);
output.print(" ");
}
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;}
}
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.
So I fixed my program but the problem is that after replacing all the blank spaces with tildes i have to output the text to a file that has been closed. How would I re-open the file for output and input something in?
//Name: Allen Li
//Program file: Vowels.Java
//Purpose: Using File IO, read a file's input and output this text to a new text file
//When outputting, all blank spaces will be changed to tildes and there will be a count of each vowel(AEIOU)
import java.util.Scanner; //input
import java.io.File; //IO
import java.io.IOException; //IO exception class
import java.io.FileWriter; //file output
import java.io.FileReader; //file input
import java.io.FileNotFoundException; //if file isnt found, file not found class
public class Vowels { //class
public static void main(String[] args) { //main method
try { //try block
FileReader poetry = new FileReader("poetry.txt");
FileWriter dentist = new FileWriter(
"LI_ALLEN_dentist.txt");
int a;
while ((a = poetry.read()) != -1) {
dentist.write(a);
System.out.print((char) a); //print the file to the monitor
}
poetry.close();
dentist.close();
Scanner inFile = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
int numOfVowelsA = 0; //count #s of A/E/I/O/U vowels
int numOfVowelsE = 0;
int numOfVowelsI = 0;
int numOfVowelsO = 0;
int numOfVowelsU = 0;
while (inFile.hasNext()) {
String sentence = inFile.next() /* ("\\S+") */;
for (int i = 0; i <= sentence.length() - 1; i++) {
if (sentence.toLowerCase().charAt(i) == 'a') {
numOfVowelsA++;
}
if (sentence.toLowerCase().charAt(i) == 'e') {
numOfVowelsE++;
}
if (sentence.toLowerCase().charAt(i) == 'i') {
numOfVowelsI++;
}
if (sentence.toLowerCase().charAt(i) == 'o') {
numOfVowelsO++;
}
if (sentence.toLowerCase().charAt(i) == 'u') {
numOfVowelsU++;
}
}
}
System.out.println();
System.out.println("There are " + numOfVowelsA
+ " A vowels in this file of text");
System.out.println("There are " + numOfVowelsE
+ " E vowels in this file of text.");
System.out.println("There are " + numOfVowelsI
+ " I vowels in this file of text.");
System.out.println("There are " + numOfVowelsO
+ " O vowels in this file of text.");
System.out.println("There are " + numOfVowelsU
+ " U vowels in this file of text. ");
Scanner tildes = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
while (tildes.hasNext()) {
String replace = tildes.nextLine();
replace = replace.replaceAll(" ", "~");
System.out.println();
System.out.print(replace);
}
} catch (FileNotFoundException i) {
System.out.println("The file you are trying to use as input is not found. " + i);
} catch (IOException i) {
System.out.println("There is an issue with the input or output file. " + i);
}
}
}
You didn't close inFile. Close inFile first and then you are able to open it again in tildes.
Close it before Scanner tildes = new Scanner(...); line.
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.