Consider this code:
private static void colourRead(String s) throws IOException {
FileReader readhandle = new FileReader("C:\\****\\****");
BufferedReader br = new BufferedReader(readhandle);
String line = null;
while ((line = br.readLine()) != null) {
ColourInput(); //there's an error here
}
br.close();
readhandle.close();
}
private static void ColourInput(String s) {
char letter;
String fullWord;
Scanner kb = new Scanner(System.in);
System.out.print("Enter whatever: ");
fullWord = kb.nextLine();
System.out.println(fullWord);
for (int i = 0; i < fullWord.length(); i++) {
letter = fullWord.charAt(i);
switch (Character.toUpperCase(letter)) {
case 'A': {
Blue();
}
break;
}
}
}
Is it possible for me to carry the
line
variable from the colourRead method, and somehow assign it to the
fullWord
variable in the ColourInput() method?
I'm trying to read a text file, and output certain colours associated to each letter. I don't want to create a new switch statement in the colourRead method because apparently, this is a bad programming practice.
Any help please?
If you're still unsure of what I'm asking I'll re-edit
EDIT: The problem is that after calling the ColourInput(line) method, the Scanner method comes in to work (original code). I don't want to remove my Scanner method, I want it to 'skip' the scanner method, and continue into the for loop and switch statements.
You're not passing the string to your call of ColourInput
Try
ColourInput(line);
It is also worth mentioning that your code that reads the file is not safe, you should try to read the file, catch the IOException and close the file in a finally clause, if your code crashes somewhere in the while loop your file might remain open
If I understand correctly you want to be able to repeat the functionality of the ColourInput method with the results of the the ColourRead method.
private static void colourRead() throws IOException
{
FileReader readhandle = new FileReader("C:\\****\\****");
BufferedReader br = new BufferedReader(readhandle);
String line = null;
while((line = br.readLine()) != null)
{
ColourText(line); //there's an error here
}
br.close();
readhandle.close();
}
private static void ColourInput()
{
String fullWord;
Scanner kb = new Scanner(System.in);
System.out.print("Enter whatever: ");
fullWord = kb.nextLine();
System.out.println(fullWord);
ColourText(fullWord);
}
private static void ColourText(String text)
{
char letter;
for (int i = 0; i < text.length(); i++)
{
letter = text.charAt(i);
switch(Character.toUpperCase(letter))
{
case 'A':
{
Blue();
}
break;
}
}
This would let you color the text whether it is read from the file or input from the keyboard(using the ColourText method to change the color). But as other people have mentioned you should add to the file reading code as well.
Edit: You could also remove the String s variables from the first two methods since they are not being used in the methods anywhere.
Related
I'm a beginner and need some help. I'm trying to scan a text file into an array line by line, but omitting one line. My text file is
i am
you are
he is
she is
it is
I want to create a method that will scan this and put elements into an array with an exception for one line (that is chosen by entering the String as a parameter for the method). Then erase the original text file and print there the created array (without that one deleted line). Sorry, I suck at explaining.
I have tried this:
public static void deleteLine(String name, String line) throws IOException {
String sc = System.getProperty("user.dir") + new File("").separator;
FileReader fr = new FileReader(sc + name + ".txt");
Scanner scan = new Scanner(fr);
int n = countLines(name); // a well working method returning the number if lines in the file (here 5)
String[] listArray = new String[n-1];
for (int i = 0; i < n-1; i++) {
if (scan.hasNextLine() && !scan.nextLine().equals(line))
listArray[i] = scan.nextLine();
else if (scan.hasNextLine() && scan.nextLine().equals(line))
i--;
else continue;
}
PrintWriter print = new PrintWriter(sc + name + ".txt");
print.write("");
for (int i = 0; i < n-2; i++) {
print.write(listArray[i] + "\n");
}
print.close()
}
I get an error "Line not found" when I enter: deleteLine("all_names","you are") (all_names is the name of the file). I'm sure the problem lies in the for-loop, but I have no idea why this doesn't work. :(
//SOLVED//
This code worked after all. Thanks for answers!
public static void deleteLine(String name, String line) throws IOException{
String sc = System.getProperty("user.dir") + new File("").separator;
FileReader fr = null;
fr = new FileReader(sc+name+".txt");
Scanner scan = new Scanner(fr);
int n = LineCounter(name);
String[] listArray = new String[n-1];
for (int i = 0; i < n-1; i++) {
if (scan.hasNextLine()) {
String nextLine = scan.nextLine();
if (!nextLine.equals(line)) {
listArray[i] = nextLine;
}
else i--;
}
}
PrintWriter print = new PrintWriter(sc+name+".txt");
print.write("");
for(int i=0;i<n-1;i++){
print.write(listArray[i]+System.lineSeparator());
}
print.close();
}
You are reading the lines twice scan.nextLine() while comparing and because of that you run out of the lines.
Replace your loop with this one or similar
for (int i = 0; i < n; i++) {
if (scan.hasNextLine()) {
String nextLine = scan.nextLine();
if (nextLine.equals(line)) {
listArray[i] = nextLine;
}
}
}
Have a look at how you are comparing String objects. You should use the equals method to compare a String's content. Using operators like == and != compares if the String objects are identical.
Now after using equals correctly have a look at how you are using nextLine. Check its Javadoc
I feel LineCounter(name) works because you did not put a ".txt" there. Try removing the ".txt" extension from the file name in the Filereader and Printwriter objects and see if it works. Usually in windows, the extension is not a part of the file name.
Here's an alternative (easier) solution to do what you want, using easier to understand code. (I think)
Also it avoids multiple
loops, but uses a single Java 8 stream to filter instead.
public static void deleteLine(String name, String line) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(name));
lines = lines.stream().filter(v -> !v.equals(line)).collect(Collectors.toList());
System.out.println(lines);
// if you want the String[] - but you don't need it
String[] linesAsStringArr = new String[lines.size()];
linesAsStringArr = lines.toArray(linesAsStringArr);
// write the file using our List<String>
Path out = Paths.get("output.txt"); // or another filename you dynamically create
Files.write(out, lines, Charset.forName("UTF-8"));
}
I want to send each line one at a time to the calling method from a text file.
I am trying to read a file line by line and populated each line to a string array. i.e. each line is considered to be one element in string array. Can anyone please help me how to achieve. But after doing this I an unable to send individual elements from the array to the calling function.. Can anyone please help me how to achieve this
package fileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class stringBuffer{
public static void main(int args[])
{
String line = readFile();
writeFile(line);
}
public static String readFile()
{
String inputfile = null;
Scanner sc = new Scanner(System.in);
String[] temp = new String[100];
System.out.println("Please enter the input file location C:\\text.txt");
inputfile = sc.nextLine();
Scanner r = null;
try
{
r = new Scanner(new File(inputfile));
String i = null;
for (int x;r.hasNextLine() && (i = r.nextLine()) != null; x++ ) {
System.out.println(i);
temp[x] = i;
}
r.close();
if(temp == null) return null;
String str[] = new String[temp.length];
for(int y =0; y < temp.length; y++)
{
// How to send each element to the called function here str[i] =
}
}
catch (FileNotFoundException ex)
System.out.println("The file could not be found! "+ex.getMessage());
return null;
}
}
If you want to send each line back to the function that called it, you'll have to send back the entire array or as #MJSG said, call writeFile() in the readFile() method.
So either:
change it to public static String[] readFile() and loop through the elements in main, calling writeFile(lines[i]) for each OR
Change the end of readFile() such that it calls writeFile(temp[y])
When I run program it never stops, and don't know how to make (for each line) different v number (gives me syntax error) thanks for helping.
file format each line has string int string string
public static void main(String[] args) throws FileNotFoundException, IOException {
String filelocation = "location";
filelocation = JOptionPane.showInputDialog("Enter file address");
BufferedReader inFile = new BufferedReader(new FileReader(filelocation)); //using BufferedReader to get readLine function
ArrayList<Vehicle> VehicleList = new ArrayList<Vehicle>();
int counter = 1;
String dataRow = null;
dataRow= inFile.readLine();
while ( dataRow != null){
try{
String[] temp = dataRow.trim().split("\\s+");
Vehicle v(counter) = new Vehicle (temp[0], Integer.parseInt(temp[1]), temp[2], temp[3], temp[4]);
VehicleList.add(v1);
dataRow= inFile.readLine();
}
catch(Exception e){}
}
inFile.close();
System.out.println(VehicleList);
System.out.println(v1);
}
As has been been said, you are most likely getting an exception within your while loop.
But the main problem with that is dataRow = inFile.readLine() being in the while loop.
while ( dataRow != null){
try{
String[] temp = dataRow.trim().split("\\s+");
Vehicle v(counter) = new Vehicle (temp[0], Integer.parseInt(temp[1]), temp[2], temp[3], temp[4]);
VehicleList.add(v1);
dataRow= inFile.readLine(); // <---shouldn't be in while loop
}
catch(Exception e){}
}
inFile.close();
System.out.println(VehicleList);
System.out.println(v1);
}
So what happens is, an exception is thrown, and then jumps to the catch block without ever changing the value of dataRow!
So everytime the while loop is executed, it is actually comparing dataRow to the first value you set it as.
You can get around this by changing the code as in the example below:
while((dataRow = inFile.readLine()) != null){
try {
//some stuff
}
catch(Exception e){
//some other stuff
}
}
Make sure to remove the line you have before the while loop that is dataRow = inFile.readLine()
So with this, it will behave more or less how you wanted it to. If you wanted to ignore the thrown exceptions, this will continue to process the file until the end. The line where the exception was thrown will be skipped.
You can't assign Dynamic variable names. Java is a strongly type language.
What you can do, is save it on a list, and use the index for getting and setting it.
Your code should be as follow:
String[] temp = dataRow.trim().split("\\s+");
Vehicle v = new Vehicle (temp[0], Integer.parseInt(temp[1]), temp[2], temp[3], temp[4]);
VehicleList.add(v);
System.out.println(v);
dataRow= inFile.readLine();
For getting use
VehicleList.get(index)
For setting use
VehicleList.set(index, VEHICLE)
The most likely cause to the loop not terminating is an exception within the read loop (you consume the exception and try to continue). Based on your example, I think that you have a mismatch on input from split versus the Vehicle constructor. Also as you found out, you cannot have dynamic variable names such that Vehicle v(counter) = new Vehicle(... gives a syntax exception.
See if this version helps show you where the problem is.
public static void main(String[] args) throws FileNotFoundException, IOException {
String filelocation = "location";
filelocation = JOptionPane.showInputDialog("Enter file address");
BufferedReader inFile = new BufferedReader(new FileReader(filelocation)); //using BufferedReader to get readLine function
ArrayList<Vehicle> VehicleList = new ArrayList<Vehicle>();
int counter = 0;
String dataRow = null;
dataRow= inFile.readLine();
try{
while ( dataRow != null){
String[] temp = dataRow.trim().split("\\s+");
if (temp.length != 5)
throw new Exception("split returned "+temp.length);
Vehicle v = new Vehicle (temp[0], Integer.parseInt(temp[1]), temp[2], temp[3], temp[4]);
VehicleList.add(v);
System.out.println(v);
dataRow= inFile.readLine();
}
}
catch(Exception e){
e.printStackTrace();
}
finally {
inFile.close();
}
System.out.println(VehicleList);
}
I am trying to scan through text files and add them to a map, the map and everything is working. However, the scanner seems to be stopping when it comes to a 'enter' in the text file, or a blank line. This is my problem
here is my block of code for the scanner/mapper
class OneButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent evt)
{
final JFileChooser oneFC = new JFileChooser();
oneFC.showOpenDialog(AnalysisFrame.this);
String newLine = null;
oneFC.getName(null);
int returnVal = 0;
File fileOne = oneFC.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(fileOne);
}
catch (FileNotFoundException ex) {
Logger.getLogger(AnalysisFrame.class.getName()).log(Level.SEVERE, null,
ex);
}
inputText = input.nextLine();
String[] words = inputText.split("[ \n\t\r,.;:!?(){}]");
for(int i = 0; i < words.length; i++){
key = words[i].toLowerCase();
if (words[i].length() > 1){
if (mapOne.get(key) == null){
mapOne.put(key, 1);
}
else {
value1 = mapOne.get(key).intValue();
value1++;
apOne.put(key, value1);
}
}
}
}
}
Thanks for any help!
You should scan inside a loop until it reaches the end of the file, for example:
StringBuilder builder = new StringBuilder();
while(input.hasNextLine()){
builder.append(input.nextLine());
builder.append(" "); // might not be necessary
}
String inputText = builder.toString();
An alternative to using split could be to use a Delimiter with the Scanner and use hasNext() and next() instead of hasNextLine() and nextLine(). Try it out, see if it works.
For example:
scanner.useDelimiter("[ \n\t\r,.;:!?(){}]");
ArrayList<String> tokens = new ArrayList<String>();
while(scanner.hasNext()){
tokens.add(scanner.next());
}
String[] words = tokens.toArray(new String[0]); // optional
Also on a side note, it's not necessary to create the JFileChooser everytime:
class OneButtonListener implements ActionListener
{
private final JFileChooser oneFC = new JFileChooser();
#Override
public void actionPerformed(ActionEvent evt)
{
Not having worked with Java in a very long time I may be way off, but it looks like you call inputText = input.nextLine(); exactly once, so it makes sense that you're only getting one line. Presumably you want to call nextLine() in a loop so that it keeps giving you lines until it gets to the end of the file.
String contentsOfWholeFile = new Scanner(file).useDelimiter("\\Z").next();
In split("[ \n\t\r,.;:!?(){}]")
add \f
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");
}
}
}