Reading multiple text files java - java

I'm having trouble on reading multiple text files to fit into one scanner for example I have multiple text files that are named text1.txt, text2.txt etc... I'm trying to make it so that once the user enters which text file number they want it will bring up that data via arrays.
File txt = new File("text.txt");
void readTextFiles() throws IOException {
String line[] = new String[100];
Scanner readTextFiles= new Scanner(txt);
while (readTextFiles.hasNextLine()) {
line[q] = readTextFiles.nextLine();
if (line[q].trim() != "") {
String item[] = line[i].split(" ");
time[q] = item[0];
date[q] = item[1];
}
q++;
}
readTextFiles.close();
}
my logic works like this but its a code error:
File txt= new File("txt" + textFileNumber + ".txt");
int textFileNumber=0;`

If I understood correctly, the error you got is because the initialisation of the local variable does not precede it's use. You need to declare the textFileNumber before its usage in the string concatenation.
Further you are implementing this functionality as a method. So why not make the file number a method parameter?
public void readTextFiles(int fileNumber){
File txtFile = new File("text" + fileNumber + ".txt");
//logic
}

Related

How to rename instances of filepath scattered throughout program based on user input?

I'm pretty new to Java, so apologies if this question seems dumb, I've tried google but there's not really anything on there that matches what I'm looking for.
I am trying to get my program to take in user input and rename .txt files linked to the program with their input. My only issue is, I don't know how I would then take that input and update all the named instances of the filepath across the program. For the most part, I am passing the filepath into methods for usage, but the initial variable of filepath I have declared as a String.
Any advice on the most efficient way to update all instances of this variable at once with the new file name?
String filepath = "src/file.txt";
Here is the code I currently have for editing the file name:
public static void fileRename(){
String oldFileName = "";
String newFileName = "";
Scanner in = new Scanner(System.in);
System.out.println("Please enter old File name: ");
System.out.println("Formatted as: src/oldFileName.csv");
oldFileName = in.next();
System.out.println("Please enter new File name: ");
System.out.println("Formatted as: src/newFileName.csv");
newFileName = in.next();
File oldFile = new File(oldFileName);
File newFile = new File(newFileName);
oldFile.renameTo(newFile);
// sets filepath variable across program equal to newFileName
}
Once the user has renamed the file, I am struggling with then updating the filepath variable across the program, as it occurs multiple times within the program.
String targetExtension = ".txt";
if (args.length >= 1 ) {
int extIndex = args[0].lastIndexOf(".");
if (extIndex != -1) {
String ext = args[0].substring(extIndex);
System.out.println(ext);
if (ext.equalsIgnoreCase(".xml")){
try
{
File f = new File(args[0]);
if (!f.exists())
{
f.createNewFile();
}
args[0] = args[0].substring(0, extIndex) + targetExtension;
System.out.println(" " + args[0]);
File change = new File(args[0]);
f.renameTo(change);
}catch (IOException e)
{
e.printStackTrace();
}
}
}
you can use elseif for all the extension.

How to use "write" to get the information in a for each loop

Im currently working on a project at school, where I am to switch out a certain word in an ArrayList. The word is written several times in the list. Im going to change it with a random word from a different ArrayList. My loop currently works as I wanted to, surly I can make it better, but it works atm. The word im changing is "ADJEKTIV"
My problem is that I cant get it to write to a file. It will print out using the System.out.println to terminal, but the assignment tell us to write it to the file.
public class StoryCreator
{
private InputReader reader;
private OutputWriter writer;
private Random random;
public StoryCreator()
{
reader = new InputReader();
writer = new OutputWriter();
random = new Random();
}
public void createAdjectiveStory(String storyFilename, String adjectivesFilename, String outputFilename)
{
ArrayList<String> storyWords = reader.getWordsInFileWithScanner(storyFilename);
ArrayList<String> adjectives = reader.getWordsInFileWithScanner(adjectivesFilename);
String replaceKeyword = "ADJEKTIV";
for(String words : storyWords)
{
if(storyWords.contains("ADJEKTIV"))
{
int adjectiveNumber = random.nextInt(adjectives.size());
String randAdjective = adjectives.get(adjectiveNumber);
String story = words.replace(replaceKeyword,randAdjective);
System.out.println(story);
writer.write(storyWords, outputFilename);
}
}
}
I've gotten the text to be written in a file, but it doesn't write the file where I have replaced the words I want. It writes the file before the words are changed.
The output writer class
public class OutputWriter
{
/**
* Constructor for objects of class OutputWriter
*/
public OutputWriter()
{
}
/**
* Writes a list of words to a file. The words are separated by the 'space' character.
*
* #param output the list of words
* #param filename the name of the output file
*/
public void write(ArrayList<String> output, String filename)
{
try {
FileWriter out = new FileWriter(filename);
for(String word : output) {
out.write(word + " ");
}
out.close();
}
catch(IOException exc) {
System.out.println("Error writing output file: " + exc);
}
}
}
Hope someone knows how I can manage this.
You are looping through String word : storyWords and replacing the word object with the random word. So, far so good.
The problem I think you have is here:
String story = words.replace(replaceKeyword,randAdjective);
System.out.println(story);
writer.write(storyWords, outputFilename);
You write out the story object using System.out.println(story) but then you write out the storyWords object to the file. This storyWords list will include the old String as you haven't replaced it with story (Which has the replacement in). This is why you are seeing the old word when writing to a file.
This brings up a new issue of the replacement of the String in storyWords as trying to modify within a for-each loop will throw an exception.
I think it would be better to use a normal for loop instead of a for-each to keep the position of the String inside storyWords so you can make the replace.
for(int i = 0 ; i < storyWords.size() ; i++)
{
String word = storyWords.get(i);
if(word.contains("ADJEKTIV"))
{
int adjectiveNumber = random.nextInt(adjectives.size());
String randAdjective = adjectives.get(adjectiveNumber);
String story = word.replace(replaceKeyword, randAdjective);
System.out.println(story);
storyWords.set(i, story);
writer.write(storyWords, outputFilename);
}
}
I think that should be the kind of thing you are looking for.
I have kept the code as close as possible to what you had originally written.
I did change the storyWords.contains("ADJEKTIV") to word.contains("ADJEKTIV") making the assumption that is what you meant.

reading txt file and writing a dictionary

My objective is to eventually make a spell checker but I need a dictionary of words to do that.
Here I'm trying to allow the user to input any number of text files as long as there's a space in between the file names ("novel1.txt novel2.txt novel3.txt").
I will use every word from these novels to write to a .dat file of individual words on individual lines(i.e. a dictionary of words). However I'm getting a file not found error at Scanner read = new Scanner(new File(filenames[i])); even though I know that I have the file.
I have even tried putting it in the source package to make sure it could be found.
At the very bottom of my code is a small test I ran (commenting out the other code first) and it does indeed print "war.txt isn't a file," even though I can clearly see that I have the txt file and have typed it correctly.
Can somebody tell me why java isn't seeing my txt file or maybe doesn't think it is a normal file?
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the file names exactly.");
String userInput = in.nextLine();
String[] filenames = userInput.split(" "); // turning user input string into a string array so I can look at each string individually
// takes each individual string from filenames and turns each one into the file
// that the string should represent then adds the file's contents to my dictionary
for(int i = 0; i < filenames.length; i++){
Scanner read = new Scanner(new File(filenames[i]));
String word = null;
while(read.hasNext()){
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
}
}
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
}
I believe you do something in a wrong way. Try following example and compare it with your actual file locations.
Demo.java
import java.io.*;
class Demo {
public static void main(String[] args) throws IOException {
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
} else {
System.out.println(war + " is a file.");
}
}
}
compile and run it
javac Demo.java
java Demo
output
war.txt isn't a file.
now create in the same directory the war.txt
echo "foobar" > war.txt
run the code again
java Demo
output
war.txt is a file.
For the FileNotFoundException make sure that files are in your classpath if you insert only the filenames (for example if you use eclipse put the files on the root folder of the project).
For the war.txt issue you should do this:
File war = new File("war.txt");
if (!war.exists()) {
war.createNewFile();
}
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
This because when you do File war = new File("war.txt"); you are not creating the file, you have to explicitily create it with war.createNewFile();.
Finally, pay attention here:
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
You do two times read.next() without check read.hasNext() the second time. You should write something like that:
while(read.hasNext()){
String next = read.next();
if(next.length() >= 2){
word = next;
// write word into myDict.dat
}
System.out.println(word);
}

reading in csv file and storing in arrays

the practice question i got says that i need to
create a java code that reads in csv file with name and height.
to read a file you must get a file name from user as string.
then you must store contents of file into two arrays one for name (string) and height(real number).
You should read the file at least twice, once to check how many students are in the file (so you know how many students you need to store) and a couple more times to actually read the file (to get the names and height).
then prompt the user for name you want height of. it should output the height for userinput.
example csv file is
chris,180
jess,161
james, 174
its not much but this is all i could come up with i have no idea how to store name and height separately and use that array to output the results. and would i need to use split somewhere in the code? i remember learning it but dont know if its used in this situation
import.java.util.*;
private class StudentNameHeight
private void main (string [] args)
{
String filename;
Scanner sc = new scanner(system.in);
System.out.println("enter file name")
filename = sc.nextline();
readFile (filename);
}
private void readFile (String filename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
try
{
fileStrm = new FileInputStream(filename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
// ?
catch (IOException e)
{
if (fileStrm != null)
{
try {fileStrm.close(); } catch (IOException e2){}
}
System.out.println("error in processing" + e.getMessage());
}
}
im new to java so, any small tip or help would be great
thanks
You code looks messy. As far as I understand from your question, you are willing to read a CSV file containing two entities, one is name and another is height and store these two entities in two different data structures. I'm teaching you a simple way to accomplish this in below code snippet.
public void processCSVFile(String filePath){
try(BufferedReader fileReader = new BufferedReader(new FileReader(new File(filePath)))){
//Create two lists to hold name and height.
List<String> nameList = new ArrayList<>();
List<Integer> heightList = new ArrayList<>();
String eachLine = "";
/*
* Read until you hit end of file.
*/
while((eachLine = fileReader.readLine()) != null){
/*
* As it is CSV file, split each line at ","
*/
String[] nameAndHeightPair = eachLine.split(",");
/*
* Add each item into respective lists.
*/
nameList.add(nameAndHeightPair[0]);
heightList.add(Integer.parseInt(nameAndHeightPair[1]));
}
/*
* If you are very specific, you can convert these
* ArrayList to arrays here.
*/
}catch(IOException e1){
e1.printStackTrace();
}
}

How to get the updated file text

I am making a JFrame from where the user will be able to insert new methods in the file. If the file is not there, program will create the new file and then insert the method there. If the file is already there, it will try to create the new method with the given name but if the file contains the method with the same name, it'll give user the alert.
I am able to do all these things properly, only problem is after creating the new method in the class file, if the user again click on the Create Method button, application does not throws any alert as it is unable to read the new method name from the file. When I check the file content, I can see the new method there but somehow my code is not able to read the new code from the file. Here is the code for the same.
File f = null;
f = new File(Report.path + "//src//_TestCases//" + tc_name + ".java");
if (!f.exists()) {
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
f.createNewFile();
bw.write(testcase);
bw.close();
}
Class<?> c = Class.forName("_TestCases." + tc_name);
Method[] m = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().toLowerCase()
.equals(module_name.toLowerCase())) {
JOptionPane
.showMessageDialog(null,
"Module with the given name already exists. Please provide other name.");
return false;
}
}
List<String> lines = Files.readAllLines(f.toPath(),
StandardCharsets.UTF_8);
String text = "";
if (lines.contains(" #AfterClass")) {
text = " #AfterClass";
} else {
text = "#AfterClass";
}
lines.add(lines.indexOf(text), "#Test\npublic void " + module_name
+ "() throws Exception {\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
for (int i = 0; i < tc_values.size(); i++) {
lines.add(lines.indexOf(text), tc_values.get(i));
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
}
lines.add(lines.indexOf(text), "\n}\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
Not sure what the issue was but when I changed the logic of getting the method name from the file, it worked for me. Used scanner to read the file contents and get the method name, earlier was using the below line to get the method name from the file.
Method[] m = c.getDeclaredMethods();

Categories

Resources