Get two variables from a reading file class without duplicating code - java

I have created a class called ReadFile to load the data (numbers and number of elements) from multiple files to 2 arraylist to store both numbers of number of elements. How can I get both the number of elements which is 4 and the following numbers without duplicating the reading file codes?
Sample input file
4
1 10 9 8
public class ReadFile {
public List <Integer> getNumbers(){
List<Integer> numbers = new ArrayList<>();
File folder = new File("/Users/Mary/NetBeansProjects/Sample/src/program/pkg4/Input");
for (File file : folder.listFiles()) {
try{
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String numberOfElement = reader.readLine();
String line = reader.readLine();
for (String s : line.split("\\s+")) {
numbers.add(Integer.parseInt(s));
}
reader.close();
}catch(IOException e){
System.out.println("ERROR: There was a problem reading the file.\n" + e.getMessage());
}
}
return numbers;
}
public List <Integer> getElements(){
List<Integer> elements = new ArrayList<>();
File folder = new File("/Users/Mary/NetBeansProjects/Sample/src/program/pkg4/Input");
for (File file : folder.listFiles()) {
try{
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String numberOfElement = reader.readLine();
elements.add(Integer.parseInt(numberOfElement));
reader.close();
}catch(IOException e){
System.out.println("ERROR: There was a problem reading the file.\n" + e.getMessage());
}
}
return elements;
}
}

You can do as #jonathan Heindl suggested (read the entire fie into a String), or you can at least move the creation of the reader outside the two methods:
public void parseFile()) {
File folder = ...;
for (File file : folder.listFiles()) {
try {
// create reader for this file
...
int number = getNumber(reader);
List<Integer> = getElements(reader, number);
} catch( ... ) {
...
}
}
}
You may even want to put the element list in a map keyed with the file name.It is not clear from your comments whether there are multiple lists in a single file, so you may need to do something different to handle that case.

Related

How to load a tsv file for MALLET using FileInputStream in Java?

I want to load the flat text file passed in as 'TMFlatFile' (which is the .tsv file format to use in MALLET) into into the fileReader variable.
I have created the method, RunTopicModelling() and am having a problem with the try/except block.
I have created my File and FileInputStream objects, but dont know how to load it correctly into fileReader?
I have an error that "The method read(CharBuffer) in the type InputStreamReader is not applicable for the arguments (int)".
public class TopicModelling {
private void StartTopicModellingProcess(String filePath) {
JSONIOHelper jsonIO = new JSONIOHelper();
jsonIO.LoadJSON(filePath);
ConcurrentHashMap<String, String> lemmas = jsonIO.GetDocumentsFromJSONStructure();
SaveLemmaDataToFile("topicdata.txt" ,lemmas);
}
private void SaveLemmaDataToFile(String TMFlatFile, ConcurrentHashMap<String, String> lemmas) {
for (Entry<String, String> entry : lemmas.entrySet()) {
try (FileWriter writer = new FileWriter(TMFlatFile)) {
;
writer.write(entry.getKey() + "\ten\t" + entry.getValue() + "\r\n");
} catch (Exception e)
{
System.out.println("Saving to flat text file failed...");
}
}
}
private void RunTopicModelling(String TMFlatFile, int numTopics, int numThreads, int numIterations) {
ArrayList<Pipe> pipeList = new ArrayList <Pipe>();
// Pipes: tokenise, map to features
pipeList.add(new CharSequence2TokenSequence (Pattern.compile("\\p{L}[\\p{L}\\p{P}]+\\p{L}")));
pipeList.add(new TokenSequence2FeatureSequence());
InstanceList instances = new InstanceList (new SerialPipes(pipeList));
InputStreamReader fileReader = null;
//loads the file passed in via the TMFlatFile variable into the fileReader variable - this block I have a problem with
try {
File inFile = new File(TMFlatFile);
FileInputStream fis = new FileInputStream(inFile);
int line;
while ((line = fis.read()) != -1) {
}
fileReader.read(line);
}
fis.close();
}catch(
Exception e)
{
System.out.println("File Load Failed");
System.exit(1);
}
\\ // linking data to the pipeline
instances.addThruPipe(new CsvIterator(fileReader,Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"),3,2,1));
}
Can someone tell me what is the correct way to do this?
It's hard to say what the immediate issue is because the code sample provided looks like it's missing important parts, and would not compile as written (for example Exception e) and regex without quotes).
The data import developers guide https://mimno.github.io/Mallet/import-devel has sample code that should be a good starting point.

Read from one text file and write into two text files

I need to read from one text file(carsAndBikes.txt) and the write in either cars.txt or bikes.txt
carsAndBikes contains a list of cars and bikes and the first character of each name is C or B (C for Car and B for Bike). So far i have that but its showing cars and bikes content. Instead of the separated content.(CARS ONLY OR BIKES ONLY)
public static void separateCarsAndBikes(String filename) throws FileNotFoundException, IOException
{
//complete the body of this method to create two text files
//cars.txt will contain only cars
//bikes.txt will contain only bikes
File fr = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
Scanner scanFile = new Scanner(fr);
String line;
while(scanFile.hasNextLine())
{
line = scanFile.nextLine();
if(line.startsWith("C"))
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\cars.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
else
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\bikes.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
}
//close the file
scanFile.close();
}
You're checking if the input filename starts with a c instead of checking if the line read starts with a c.
You should also open both your output files before your loop, and close them both after the loop.
// Open input file for reading
File file = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
BufferedReader br = new BufferedReader(new FileReader(file)));
// Open bike outputfile for writing
// Open cars outputfile for writing
// loop over input file contents
String line;
while( line = br.readLine()) != null ) {
// check the start of line for the character
if (line.startsWith("C") {
// write to cars
} else {
// write to bikes
}
}
// close all files

How to compare and merge two text files?

I have two files say
abc
cdg
sfh
drt
fgh
and another file
ahj
yuo
jkl
uio
abc
cdg
I want to compare these two files and get output file as
abc
cdg
sfh
drt
fgh
ahj
yuo
jkl
uio
this is my code
public static void MergeFiles(final File priviousModifiedFilesList, final File currentModifiedFilesList,
final File ModifiedFilesList) {
FileWriter fstream = null;
out = null;
try {
fstream = new FileWriter(ModifiedFilesList, true);
out = new BufferedWriter(fstream);
}
catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("merging: " + priviousModifiedFilesList + "\n");
System.out.println("merging: " + currentModifiedFilesList);
FileInputStream fis1;
FileInputStream fis2;
try {
fis1 = new FileInputStream(priviousModifiedFilesList);
BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(fis1));
fis2 = new FileInputStream(currentModifiedFilesList);
BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(fis2));
String Line1;
String Line2;
while (((Line1 = bufferedReader1.readLine()) != null)) {
while ((Line2 = bufferedReader2.readLine()) != null) {
if (Line1.equals(Line2)) {
out.write(Line1);
}
out.write(Line2);
out.newLine();
}
out.write(Line1);
}
bufferedReader1.close();
bufferedReader2.close();
}
catch (IOException e) {
e.printStackTrace();
}
out.close();
}
it writes all the lines from first file and when the lines match it stops.
It's easy:
Read you first file line by line (you can use a Scanner for that).
For each line, write it to the output file (you can use a PrintWriter for that).
Also store the line in a HashSet.
Read your second file line by line.
For each line, check if the line is in the HashSet.
If it's not, write it to the output file.
Close your files.

In Java, I want to split an array into smaller arrays, the length of which varys with inputted text files

So far, I have 2 arrays: one with stock codes and one with a list of file names. What I want to do is input the .txt files from each of the file names from the second array and then split this input into: 1. Arrays for each file 2. Arrays for each part with each file.
I have this:
ImportFiles f1 = new ImportFiles("File");
for (String file : FileArray.filearray) {
if (debug) {
System.out.println(file);
}
try {
String line;
String fileext = "C:\\ASCIIpdbSKJ\\"+file+".txt";
importstart = new BufferedReader(new FileReader(fileext));
for (line = importstart.readLine(); line != null; line = importstart.readLine()) {
importarray.add (line);
if (debug){
System.out.println(importarray.size());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
importarray.add ("End")
This approach works to create a large array of all the files, will it be easier to change the input method to split it as it is coming in or split the large array I have?
At this point, the stock code array is irrelevant. Once I have split the arrays down I know where I will go from there.
Thanks.
Edit: I am aware that this code is incomplete in terms of { } but it is only printstreams and debugging missed off.
If you want to get a map with a filename and all its lines from all the files, here are relevant code parts:
Map<String, List<String>> fileLines = new HashMap<String, List<String>>();
for (String file : FileArray.filearray)
BufferedReader reader = new BufferedReader(new FileReader(fileext));
List<String> lines = new ArrayList<String>();
while ((line = reader.readLine()) != null){
lines.add(line);
}
fileLines.put(file, lines);
}

Java Record Navigation

your valuable help needed again. I have the following code in which i am reading file contents for each file. each file is related to an individual staff. On click of a button called "show staff record", i want to show all staff file data in a GUI. but instead of all them appearing at one i want it to have navigation next and previous like in MS Access? any ideas. a code perhaps?
/*********************Calculate Staff Balance***************************/
public class calcBalanceListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File folder = new File("/register/");
filePaths = new ArrayList<String>();
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
filePaths.add(file.getPath());
}
}
}//end try
catch (Exception f) {
f.printStackTrace();
}
callDetail();
}}
/*************************************************************************/
public void callDetail() {
File f = new File(filePaths.get(indexCounter));
try{
FileReader fileReader = new FileReader(f);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String name = bufferedReader.readLine();
int id = Integer.parseInt(bufferedReader.readLine());
bufferedReader.readLine();
String address = bufferedReader.readLine();
int amount = Integer.parseInt(bufferedReader.readLine());
bufferedReader.readLine();
balanceFrame = new JFrame("Monthly Staff Balance");
lID.setText("Staff ID: " + id);
lname.setText("Staff ID: " + name);
laddress.setText("Staff ID: " + address);
lbalance.setText("Staff ID: " + amount);
balanceFrame.add(lID);
balanceFrame.add(lname);
balanceFrame.add(laddress);
balanceFrame.add(lbalance);
bufferedReader.close();
fileReader.close();
}//end try
catch(IOException z){
z.printStackTrace();
} //end catch
}
/***************************************************************************************************/
What you might do is that instead of reading the files, in your loop, you might want to iterate and obtain the file location of all the files in your directory and place their address inside an array list.
You can then use the back/forward buttons to traverse the array list, each time loading the file according to which location you are currently in your array list.
List<String> filePaths = new ArrayList<String>();
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
filePaths.add(file.getPath());
}
}
}
All you need to do is to have some global counter which you use to then navigate the array list when the forward/backward buttons are pressed. Once the button is pressed, load the appropriate file (determined by the counter) and display its content.

Categories

Resources