I am having this issue getting the file input from one class and using it in another. So what happens is I have a file called readFile.java that reads in the line of a txt file. I have another file that I am using to evaluate a stack that I want to use the file input. So all in all, I am trying to find a way to replace my testInput string in my evalStack.java file with the file input from the readFile.java.
Here is the readFile.java:
import java.util.Scanner;
import java.io.*;
public class readFile {
String fname;
public readFile() {
System.out.println("Constructor");
getFileName();
readFileContents();
}
public void readFileContents()
{
boolean looping;
DataInputStream in;
String line;
int j, len;
char ch;
/* Read input from file and process. */
try {
in = new DataInputStream(new FileInputStream(fname));
looping = true;
while(looping) {
/* Get a line of input from the file. */
if (null == (line = in.readLine())) {
looping = false;
/* Close and free up system resource. */
in.close();
}
else {
System.out.println("line = "+line);
j = 0;
len = line.length();
for(j=0;j<len;j++){
System.out.println("line["+j+"] = "+line.charAt(j));
}
}
} /* End while. */
} /* End try. */
catch(IOException e) {
System.out.println("Error " + e);
} /* End catch. */
}
public void getFileName()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter file name please.");
fname = in.nextLine();
System.out.println("You entered "+fname);
}
}
This is the evalStack.java:
import java.util.Scanner;
import java.io.*;
public class evalStack {
static String testInput = "(6+3) + (3-2)";
//This is the line I want to replace with the input the readFile gives me.
public static void main(String[] args){
int maxLength = testInput.length();
stackOb eval = new stackOb(maxLength);
boolean test = false;
//Evaluate and check parenthesis
for(int i = 0; i < testInput.length(); i++)
{
char a = testInput.charAt(i);
if(a=='(')
{
eval.push(a);
}
else if(a==')')
{
if(eval.empty() == false)
{
eval.pop();
}
else
{
test = true;
System.out.println("The equation is a not valid one.");
System.exit(0);
}
}
else
{
continue;
}
}
if(eval.empty() == true && test == false)
{
System.out.println("The equation is a valid one.");
}
else
{
System.out.println("The equation is a not valid one.");
}
}
Add the line import readFile; to the top of evalStack.java
Change input: static String testInput = new readFile().readFileContents();
Change return type: public String readFileContents()
Replace j = 0; with return line;
That will make it evaluate the first line.
Related
im a first year computer science student learning java and im trying to read a csv file line by line and convert each row to an object, then create an array out of these objects with each element separated by a comma ",". Program keeps returning unusual error: method readFile() in class cannot be applied to given types. im not sure what to do.
main class:
import java.io.*;
import java.util.*;
public class FlightOperations
{
static String fileName = "LaxData.csv";
public static void main(String[] args)
{
// Parsing a CSV file into Scanner class constructor
Scanner sc = new Scanner(System.in);
int fileLength = 0;
fileLength = getFileCount(fileName);
int again = 0;
Date[] LAXarray = new Date[fileLength];
LAXarray = readFile(fileName, fileLength);
menu(LAXarray, sc);
do
{
try
{
System.out.println("\n\nRun program? (1)YES (2)NO");
again = sc.nextInt();
if(again == 1)
{
menu(LAXarray, sc);
}
else
{
System.exit(1);
}
}
catch (InputMismatchException exception)
{
System.out.println("\nInvalid input");
sc.next();
}
}
while (again != 1 || again != 2);
sc.close(); // closes the scanner
}
readFile class:
public static Date[] readFile(String fileName)
{
FileInputStream fileStream = null;
InputStreamReader Read;
BuffferedReader bufRead;
/* int fileLength = getFileLength(fileName); */
String line;
Date[] LAXarray = new Date[getFileCOunt(fileLength)];
int LAXIndex = 0;
try
{
fileStream = new FileInputStream(fileName);
Read = new InputStreamReader(fileStream);
bufRead = new BufferedReader(Read);
line = bufRead.readLine();
for(int i = 1; i < fileLength; i++)
{
line = bufRead.readLine();
LAXarray[i] = processLine(line);
}
}
catch(IOException errorDetails)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in fileProcessing: " + errorDetails.getMessage());
}
return LAXarray;
}
Changes: delete the first two characters of each word with the length of 4 and more characters
example: original 'qwerty', new 'erty'
A 'word' should be considered a continuous sequence of Cyrillic or Latin characters.
I wrote something like this, but output string is in line, but I need input text with indent characters.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Part1 {
// getting input string from the file
public static String getInput(String fileName) {
StringBuilder sb = new StringBuilder();
try {
Scanner scanner = new Scanner(new File(fileName), "UTF-8");
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append(System.lineSeparator());
}
scanner.close();
return sb.toString().trim();
} catch (IOException ex) {
ex.printStackTrace();
}
return sb.toString();
}
// deleting the first two characters of each word with the length of 4 and more characters
public static void convert() {
try (BufferedReader in = new BufferedReader(new FileReader("part1.txt"))) {
String line;
StringBuilder result = new StringBuilder();
while ((line = in.readLine()) != null) {
String[] wordsInLine = line.split("[.,!?\\-\\s\\n]+");
for (String string : wordsInLine) {
if (isLongerThanFour(string) && defineLocale(string) == "latn") {
result.append(string.substring(2) + " ");
} else if (isLongerThanFour(string) && defineLocale(string) == "cyrl") {
result.append(string.substring(4) + " ");
} else {
result.append(string + " ");
}
}
}
System.out.println(result);
}catch(IOException e){
e.getMessage();
}
}
// checking for right length of current word
public static boolean isLongerThanFour(String string){
return string.length() >= 4;
}
// define language of input word(one of cyrillic of latin languages)
private static String defineLocale(String string) {
char ch = string.charAt(0);
if (Character.isAlphabetic(ch)) {
if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.CYRILLIC)) {
return "cyrl";
} else if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.BASIC_LATIN)){
return "latn";
}
}
return "none";
}
public static void main(String[] args){
Part1.convert();
}
}
Can you point on my mistakes or suggest cleaner solution.
Thank you in advance.
public class Converter {
//helper enum
enum Language {
cyr,
lat,
none
}
// if you have to return more that two types of values then use enum
private static Language defineLocale(String string) {
char ch = string.charAt(0);
if (Character.isAlphabetic(ch)) {
if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.CYRILLIC)) {
return Language.cyr;
} else if (Character.UnicodeBlock.of(ch).equals(Character.UnicodeBlock.BASIC_LATIN)){
return Language.lat;
}
}
return Language.none;
}
public void convert() {
try (BufferedReader in = new BufferedReader(new FileReader("part1.txt"))) {
String line;
StringBuilder result = new StringBuilder();
while ((line = in.readLine()) != null) {
String[] wordsInLine = line.split(" ");
for (String s : wordsInLine) {
if (s.length() > 3) {
switch (defineLocale(s)) {
case cyr:
result.append(s.substring(4));
break;
case lat:
result.append(s.substring(2));
break;
default:
result.append(s);
}
} else result.append(s);
result.append(" ");
}
result.append("\n");//all you were missing
}
System.out.println(result);
}catch(IOException e){
e.getMessage();
}
}
public static void main(String[] args){
new Converter().convert();
}
}
I hope this does not need any further explanation but dont be shy to ask if you dont understand something.
So, I was wondering if it's possible to save values from an ArrayList to a file, such as "inputs.txt". I've seen a question similar to this: save changes (permanently) in an arraylist?, however that didn't work for me, so I'm wondering if I'm doing something wrong. Here are my files:
Main.class
package noodlegaming.geniusbot.main;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Logger;
public class Main {
public static Random rand = new Random();
public static void readFileByLine(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
SentencesToUse.appendToInputtedSentences(scanner.next().toString());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
static File inputsFile = new File("inputs.txt");
static PrintWriter printWriter = new PrintWriter(inputsFile);
public static void main(String[] args) throws IOException, InterruptedException {
if(!inputsFile.exists()) {
inputsFile.createNewFile();
}
readFileByLine("inputs.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Hello, welcome to GeniusBot. Shortly, you will be speaking with a computer that learns from what you say.");
System.out.println("Because of this circumstance, we ask that you do not type any curses, swear words, or anything otherwise considered inappropriate,");
System.out.println("as it may come back to the light at a time you don't want it to.");
System.out.println("Please note that your responses won't be saved if you close the program.");
System.out.println("If you type printInputsSoFar, a list of all the stuff you've typed will be printed.");
System.out.println("If you type printInputsLeft, the number of inputs you have left will be printed.");
System.out.println("If you type clearInputs, the program will be closed and the inputs.txt file deleted, " +
"\nand recreated upon startup.");
System.out.println("Starting up GeniusBot.");
Thread.sleep(3000);
System.out.println("Hello! I am GeniusBot!");
br.readLine();
System.out.println("" + SentencesToUse.getBeginningSentence() + "");
for (int i = 0; i < 25; i++) {
String response = br.readLine();
if (response.equals("printInputsSoFar")) {
for (int j = 1; j < SentencesToUse.inputtedSentences.size(); j++) {
System.out.println(SentencesToUse.inputtedSentences.get(j));
}
i--;
} else if (response.equals("printInputsLeft")) {
int inputsLeft = 25 - i;
System.out.println("You have " + inputsLeft + " inputs left.");
i--;
} else if (response.equals("clearInputs")) {
printWriter.close();
inputsFile.delete();
Thread.currentThread().stop();
} else {
SentencesToUse.appendToInputtedSentences(response);
printWriter.println(response);
printWriter.flush();
int inputtedSentence = Main.rand.nextInt(SentencesToUse.inputtedSentences.size());
String inputtedSentenceToUse = SentencesToUse.inputtedSentences.get(inputtedSentence);
System.out.println(inputtedSentenceToUse);
}
if (i == 24) {
System.out.println("Well, it was nice meeting you, but I have to go. \nBye.");
Thread.currentThread().stop();
printWriter.close();
}
}
}
}
SentencesToUse.class:
package noodlegaming.geniusbot.main;
java.util.ArrayList;
import java.util.List;
public class SentencesToUse {
public static String[] beginningSentences = {"What a lovely day!", "How are you?", "What's your name?"};
static int beginningSentence = Main.rand.nextInt(beginningSentences.length);
static String beginningSentenceToUse = beginningSentences[beginningSentence];
public static String getBeginningSentence() {
return beginningSentenceToUse;
}
public static List<String> inputtedSentences = new ArrayList<String>();
public static void appendToInputtedSentences(String string) {
inputtedSentences.add(string);
}
public static void clearInputtedSentences() {
inputtedSentences.clear();
}
}
As stated in the comments, use a PrintWriter to write the values to a file instead:
PrintWriter pw = new PrintWriter(fos);
for (int i = 0; i < SentencesToUse.inputtedSentences.size(); i++) {
pw.write(SentencesToUse.inputtedSentences.get(i)+"\n"); // note the newline here
}
pw.flush(); // make sure everything in the buffer actually gets written.
And then, to read them back again:
try {
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
SentencesToUse.inputtedSentences.ass(sc.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The pw.flush(); is incredibly important. When I was first learning java, I can't tell you how many hours I spent debugging because I didn't flush my streams. Note also the "\n". This ensures that there will be a newline, and that your sentences don't just run together in one giant blob. If each one already has a newline, then that's not necessary. Unlike print vs println, there is no writeln. You must manually specify the newline character.
So here I have code I have HashMap made up by the words in file, I am adding words and writing them on file and it works, but when I use my remove function for some reaseon doesnt do anything here is the code :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
public static int value = 1;
private static Scanner input;
public static Scanner in = new Scanner(System.in);
public static Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) throws FileNotFoundException {
readFile();
System.out.println("Enter number of function wanted" + "\n1 to add"
+ "\n2 for searching by prefix" + "\n3 for deleting");
int choice = in.nextInt();
if (choice == 1) {
System.out.println("enter words seprated by comma");
String wd = in.next();
add(wd);
}
if (choice == 2) {
System.out.println("Enter prefix");
String wd = in.next();
prefixSearch(wd);
}
if (choice == 3) {
System.out.println("ENTER word to delete");
String wd = in.next();
remove(wd);
}
}
public static void readFile() throws FileNotFoundException {
input = new Scanner(file);
boolean done = false;
int value = 1;
while (input.hasNext()) {
String word = input.next().toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
map.put(line[j], value);
value++;
done = true;
}
}
if (done == true) {
System.out.println("Succes");
}
}
public static void prefixSearch(String wd) {
System.out.println("Enter prefix");
String prefix = wd.toLowerCase();
for (Map.Entry<String, Integer> key : map.entrySet()) {
if (key.getKey().startsWith(prefix)) {
System.out.println(key.getKey());
}
}
}
public static void add(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
if (!map.containsKey(line[j])) {
map.put(line[j], value);
value++;
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
continue;
}
}
if (done == true) {
System.out.println("Success");
}
}
public static void remove(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
for (Map.Entry<String, Integer> key : map.entrySet()) {
if (key.getKey().equals(line[j])) {
map.remove(key.getKey(), key.getValue());
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
continue;
}
}
}
if (done == true) {
System.out.println("Succes");
}
}
}
Every other method is working just fine, but remove. Is there something wrong with the loops, maybe use more optimal way or?
The reason for failure is that you're trying to change the map while iterating the entries. As with any collection - if you try to modify it while iterating it you'll get ConcurrentModificationException.
Further, there's a redundant inner for-loop (redundant because the whole purpose of a map is that you won't have to iterate it when you're looking for a specific value/s) which means that you'll try to override the file many times when only once is sufficient.
public static void remove(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
map.remove(line[j]);
}
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
if (done == true) {
System.out.println("Success");
}
}
The issues that I can see in your code are the following:
You forgot a quote when defining the file:
public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt")
should be:
public static File file = new File("C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
The remove() function in a map receives only one parameter, which is the key of the entry you want to remove, so:
map.remove(key.getKey(), key.getValue());
should be:
map.remove(key.getKey());
Also, since your getting the entrySet of your map, maybe you should consider renaming the key variable in the rename() function to entry.
I read two files (a large file and a small file)
The first file contains both capital letters and small letters
But second file contains just capital letters.
Program first extract capital letters from first(large file) file and then compare with second file (that contains just capital letters).
My code works well when the large files are small, But when my file size is about 400MB the program show an internal error "Java Out of Memory Error".
Here is my code:
public class SequenceComparator {
private ArrayList<Sequence> bigSequences;
private ArrayList<Sequence> smallSequences;
public SequenceComparator() {
bigSequences = new ArrayList<Sequence>();
smallSequences = new ArrayList<Sequence>();
}
private String splitUpperSequences(String bigSeq) {
StringBuilder sb = new StringBuilder();
for (char c : bigSeq.toCharArray()) {
if (Character.isLetter(c) && Character.isUpperCase(c)) {
sb.append(c);
}
}
return sb.toString();
}
public void readBigSequences() throws FileNotFoundException {
Scanner s = new Scanner(new FileReader("test_ref_Aviso_bristol_k_31_c_4.fa"));
while (s.hasNextLine()) {
String title = s.nextLine();
if (!title.startsWith(">")) {
continue;
}
String seq = s.nextLine();
Sequence sequence = new Sequence(title, splitUpperSequences(seq).trim());
bigSequences.add(sequence);
}
s.close();
}
public void readSmallSequences() throws FileNotFoundException {
Scanner s = new Scanner(new FileReader("SNP12K.fasta"));
while (s.hasNextLine()) {
String title = s.nextLine().trim();
if (!title.startsWith(">")) {
continue;
}
String seq = s.nextLine().trim();
Sequence sequence = new Sequence(title, seq);
smallSequences.add(sequence);
}
s.close();
}
public void printSeqArray(ArrayList<Sequence> seqArray) {
for (Sequence sequence : seqArray) {
System.out.println(sequence);
}
}
private void reportNotFoundSeqs(ArrayList<Sequence> notFoundSeqs) {
System.out.println("Sequence that is not similar with big file:\n\n");
printSeqArray(notFoundSeqs);
}
public void comparison() {
int bigLength = bigSequences.size();
int smallLength = smallSequences.size();
System.out.println("Sequences Length of big file is " + bigLength);
System.out.println("Sequences Length of small file is " + smallLength);
System.out.println("\n");
if (bigLength > smallLength) {
System.out.println("big file has " + (bigLength - smallLength) + " sequence more than smal file");
} else {
System.out.println("small file has " + (smallLength - bigLength) + " sequence more than big file");
}
System.out.println("\n");
int s = 0;
ArrayList<Sequence> notFoundSeqs = new ArrayList<Sequence>();
for (Sequence smalSeq : smallSequences) {
if (bigSequences.contains(smalSeq)) {
s++;
} else {
notFoundSeqs.add(smalSeq);
}
}
System.out.println("Tow files are similar in " + s + " point");
System.out.println("\n");
reportNotFoundSeqs(notFoundSeqs);
}
public ArrayList<Sequence> getBigSequences() {
return bigSequences;
}
public ArrayList<Sequence> getSmallSequences() {
return smallSequences;
}
static public void main(String args[]) throws FileNotFoundException {
SequenceComparator sc = new SequenceComparator();
System.out.println("Reading files...");
long befor = System.currentTimeMillis();
sc.readBigSequences();
System.out.println("\nBig file upper sequences:\n");
sc.printSeqArray(sc.getBigSequences());
sc.readSmallSequences();
sc.comparison();
long afer = System.currentTimeMillis();
System.out.println("Time: "+((afer-befor)/1000)+" Seconds"); }
class Sequence {
private String title;
private String seq;
public Sequence(String title, String seq) {
this.seq = seq;
this.title = title;
}
public Sequence() {
}
public String getSeq() {
return seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "\nTitle: " + title + "\n" + "Sequence: " + seq + "\n";
}
#Override
public boolean equals(Object obj) {
Sequence other = (Sequence) obj;
return seq.equals(other.seq);
}
}
}
What can i do?
You are loading the whole file content into your memory. That's why you got the Out of Memory Error. Try instead to create a temp files of equal format and the compare both files line by line. Delete the temp file at the end.
Example:
private File prepareFile(String rawFirstFile) throws FileNotFoundException, IOException {
File tempFile = new File("rawFirstFile_temp.dat");
try(BufferedReader br = Files.newBufferedReader(new File(rawFirstFile).toPath());
BufferedWriter wr = Files.newBufferedWriter(tempFile.toPath(), StandardOpenOption.WRITE)){
String line = null;
while ((line = br.readLine()) != null) {
//
// change the raw line, save filtered data as new line in your temp file
// what ever you want. example:
// title1,seq1
// title2,seq2
// ...
//
wr.write(changeLine(line));
wr.newLine();
}
return tempFile;
}
}
public void compareFiles(String firstFile, String seconFile) throws FileNotFoundException, IOException{
File tempFirstFile = prepareFile(firstFile);
File secondFile = new File(seconFile); // maybe need to prepare too
try(BufferedReader br1 = Files.newBufferedReader(tempFirstFile.toPath());
BufferedReader br2 = Files.newBufferedReader(secondFile.toPath())){
String line1File = null;
String line2File = null;
// line by line
while ((line1File = br1.readLine()) != null && (line2File = br2.readLine()) != null ) {
//
// compare them
//
}
} finally {
if(tempFirstFile != null){
//tempFirstFile.deleteOnExit();
Files.delete(tempFirstFile.toPath()); // has no effect if deleteOnExit was called!
}
}
}
private String changeLine(String rawLine) {
//TODO
return rawLine;
}
edit: changed try-catch to try-with statement to get the answer more smarter
You should perform a byte by byte comparison, not line by line as mentioned by dit. If the source of the file is unknown, using readLine() is prone to attack.