import java.io.*;
import java.io.File;
import java.io.FilenameFilter;
public class YDSearch{
public void listFiles(String dir) throws IOException{
File directory = new File(dir);
if (!directory.isDirectory()) {
System.out.println("No directory provided");
return;
}
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
//if the file extension is .mp3 return true, else false
return name.endsWith(".mp3")||name.endsWith(".mp4")||name.endsWith(".3gp")
||name.endsWith(".mov")||name.endsWith(".avi")||name.endsWith(".wmv");
}
};
String[] filenames = directory.list(filefilter);
DataOutputStream output = new DataOutputStream(new FileOutputStream("C:/Users/Jonathan/Desktop/YouDetect/SearchByFileType/AllMediaFiles.dat"));
for (String name : filenames) {
output.writeUTF(dir + name);
}
output.close();
DataInputStream input = new DataInputStream(new FileInputStream("C:/Users/Jonathan/Desktop/YouDetect/SearchByFileType/AllMediaFiles.dat"));
DataOutputStream output2 = new DataOutputStream(new FileOutputStream("C:/Users/Jonathan/Desktop/ReadyForAnalysis.dat"));
for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
int byteCounter = 0;
int rowCounter = 0;
long bufferCounter = 0;
if(name.endsWith(".mp3")){
byte[] b = new byte[36];
int read = in.read(b, 0, 36);
if (byteCounter != 1000){
if (rowCounter == 1){
System.out.println("\n");
rowCounter = 0;
}
output2.writeUTF(org.apache.commons.codec.binary.Hex.encodeHexString(b)+ " " + dir + name);
bufferCounter ++;
rowCounter ++;
}else{
byteCounter = 0;
try{
Thread.sleep(200);
}catch(InterruptedException e) {
}
}
}
else if(name.endsWith(".mp4")){
byte[] b = new byte[29];
int read = in.read(b, 0, 29);
if (byteCounter != 1000){
if (rowCounter == 1){
System.out.println("\n");
rowCounter = 0;
}
output2.writeUTF(org.apache.commons.codec.binary.Hex.encodeHexString(b)+ " " + dir + name);
bufferCounter ++;
rowCounter ++;
}else{
byteCounter = 0;
try{
Thread.sleep(200);
}catch(InterruptedException e) {
}
}
}
//System.out.println("====================");
}
output2.close();
input.close();
DataInputStream input2 = new DataInputStream(new FileInputStream("C:/Users/Jonathan/Desktop/ReadyForAnalysis.dat"));
for (String name : filenames) {
System.out.println(input2.readUTF()+"\n");
}
}
public void checkHeaderSC(String allFiles)throws IOException{
}
public static void main(String[] args) throws IOException {
YDSearch YDSearch = new YDSearch();
YDSearch.listFiles("C:/Users/Jonathan/Desktop/YD Tests/1) High Quality/");
YDSearch.listFiles("C:/Users/Jonathan/Desktop/YD Tests/2) Medium Quality/");
YDSearch.listFiles("C:/Users/Jonathan/Desktop/YD Tests/3) Low Quality/");
YDSearch.checkHeaderSC("C:/Users/Jonathan/Desktop/YouDetect/SearchByFileType/ReadyForAnalysis.dat");
}
}
Hey there, having a little issue with the above coding and hoped someone here might be able to help. This is sort of a partial version of the code as the real one has 4 more if/else if statements involved.
The program compiles and begins to run fine. It produces several results back from the file that is being read into/then out of again in input2 but then stops, produces no more results and gives the error:
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:323)
at java.io.DataInputStream.readUTF(DataInputStream.java:572)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at YDSearch.listFiles(YDSearch.java:85)
at YDSearch.main(YDSearch.java:93)
Anybody know why this might be happening and have a solution they could share?
I've also tried making the variable 'b' to be inside of an if statement but that doesn't work because of scope. If b was defined by if's then there would only need to be one if statement to output to the file
Please let me know if you've got any ideas, I'd really appreciate it :)
As far as I can see, you don't always put out an output record for every name, only for when the name matches one of your patterns. However, you do try to read an input record for every name.
Ergo, if you have any filenames that don't match the patterns you try to read more than you write, and you will get the EOF.
EDIT:
In more detail, the problem is that you get a list of all the files that end with "mp3", "mp4", "3gp", "mov", "avi or "wmv". You then process that list, and write out something into C:/Users/Jonathan/Desktop/ReadyForAnalysis.dat for each "mp3" and "mp4" file. You then assume that for each entry in your list of files, that you will have an entry in ReadyForAnalysis.dat. However, if there are any files ending in "3gp", "mov", "avi or "wmv" then this will not hold true.
Related
I asked this question earlier and I forgot to clarify what my question was so hopefully I'm actually clear this time.
I basically need help with sorting a bunch of records in a file based on their number using an algorithm like bubble sort.
I have a file with 5 records where each file consists of a number of integer type and name of 32 characters(each record size should be 36 bytes). I have to store the records into a file. **This is what I need help with:**Then sort the records based on the numbers associated with them, using a sorting algorithm like bubble sort. Another requirement is that when the program sorts the records, it shouldn't read all records in memory at once but move them in the file. For example, after the program reads the first two records, it may switch the records (because 72 > 56) and write them in the same position in the file.
We were provided with the classes to read/write and have random access to the file.
These are the records as they were provided:
72 James
56 Mark
87 John
30 Phillip
44 Andrew
I need to sort these names according to their respective numbers. My question is, what would be the best way to implement this sorting?
Here's the code for the writing class:
package test;
//write to a file
import java.io.*;
class FileWriteStreamTest {
public static void main (String[] args) {
FileWriteStreamTest f = new FileWriteStreamTest();
f.writeMyFile();
}
void writeMyFile() {
DataOutputStream dos = null;
String record = null;
int recCount = 0;
try {
File f = new File("mydata.txt");
if (!f.exists())
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
dos = new DataOutputStream(bos);
//store records into file
dos.writeBytes(72 + " James \n");
dos.writeBytes(56 + " Mark \n");
dos.writeBytes(87 + " John \n");
dos.writeBytes(30 + " Phillip \n");
dos.writeBytes(44 + " Andrew \n");
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (dos != null) {
try { dos.close(); }
catch (IOException ioe) { }
}
}
}
}
Here's the code for the reading class:
package test;
//read from a file
import java.io.*;
public class FileReadStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileReadStreamTest f = new FileReadStreamTest();
f.readMyFile();
}
void readMyFile() {
DataInputStream dis = null;
String record = null;
int recCount = 0;
try {
File f = new File("mydata.txt");
if (!f.exists()) {
System.out.println(f.getName() + " does not exist");
return;
}
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while ( (record=dis.readLine()) != null ) {
recCount++;
System.out.println(recCount + ": " + record);
}
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (dis != null) {
try { dis.close(); }
catch (IOException ioe) { }
}
}
}
}
Here's the code for the random access class:
package test;
//read or write to any place in the file
import java.io.*;
class FileRandomAccessTest {
public static void main (String[] args) {
FileRandomAccessTest f = new FileRandomAccessTest();
f.readWriteMyFile();
}
void readWriteMyFile() {
RandomAccessFile raf = null;
String s = null;
try {
File f = new File("mydata.txt");
if (!f.exists()) // check if the file exists
f.createNewFile(); // create a new file
raf = new RandomAccessFile(f, "rw"); // open a file for random access with "r", "rw"
if (raf.length() > 7) {// the size of the file
raf.seek(7); // move the file pointer
System.out.println(raf.readLine()); // read a line from the file pointer
s = raf.readLine();
System.out.println(s);
raf.seek(raf.getFilePointer() - s.length()); // get the file pointer
raf.writeBytes("Test RamdomAccessFile\n"); // write bytes
}
} catch (IOException e) {
System.out.println("Uh oh, got an IOException error!" + e.getMessage());
} finally {
// if the file opened okay, make sure we close it
if (raf != null) {
try { raf.close(); } // close the file
catch (IOException ioe) { }
}
}
}
}
My current bubble sort implementation that needs to be adapted for this problem:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Sort {
public static void bubbleSort(int[] num ) {
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag ) {
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ ) {
if ( num[ j ] < num[j+1] ) {
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int [] numbers = new int [5];
int i = 0;
while(scanner.hasNextInt()){
numbers[i++] = scanner.nextInt();
}
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
How do i go about loading a text file into a java program that i have posted below. I have tried but am out of luck, any help will be appreciated!
Thank you.
import java.io.*;
public class test1 {
public static void main(String args[]) throws Exception {
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText filename");
System.exit(0);
}
try {
FileReader infile = new FileReader(args[0]);
BufferedReader inbuf = new BufferedReader(infile);
String str;
int totalwords = 0, totalchar = 0;
while ((str = inbuf.readLine()) != null) {
String words[] = str.split(" ");
totalwords += words.length;
for (int j = 0; j < words.length; j++) {
totalchar += words[j].length();
}
}
double density = (1.0 * totalchar) / totalwords;
if (totalchar > 0) {
System.out.print(args[0] + " : " + density + " : ");
if (density > 6.0)
System.out.println("heavy");
else
System.out.println("light");
} else
System.out.println("This is an error - denisty of zero.");
infile.close();
} catch (Exception ee) {
System.out.println("This is an error - execution caught.");
}
}
}
If you are running java 8 it is a breeze with the new io streams. Advantage is on large file all text is not read into memory.
public void ReadFile(String filePath){
File txtFile = new File(filePath);
if (txtFile.exists()) {
System.out.println("reading file");
try (Stream<String> filtered = Files.
lines(txtFile.toPath()).
filter(s -> s.contains("2006]"))) {//you can leave this out, but is handy to do some pre filtering
filtered.forEach(s -> handleLine(s));
}
} else {
System.out.println("file not found");
}
}
private void handleLine(String lineText) {
System.out.println(lineText);
}
First of all, there is an easier way to read files. From Java 7 the Files and Paths classes can be used like this:
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("usage: Tut16_ReadText filename");
System.exit(0);
}
final List<String> lines = Files.readAllLines(Paths.get(args[0]));
for (String line : lines) {
// Do stuff...
}
// More stuff
}
Then, in order to start the program and get it to read a file that you specify you must provide an argument when starting the app. You pass that argument after the class name on the command prompt like this:
$ java Tut16_ReadText /some/path/someFile.txt
This passes "/some/path/someFile.txt" to the program and then the program will try to read that file.
Another method is to use a Scanner.
Scanner s = new Scanner(new File(args[0]));
while(s.hasNext()){..}
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
This is my input file:
This is a file test.
please take
notice of it.
Peace.
and this is the output:
This is a file test.
please take
notice of
I do not understant why it stops and "it." ,but it displays the word "test.".
Here's the code:
import java.io.*;
import java.util.*;
public class FileTest {
public static void readFile() throws Throwable {
File _output = new File("output.txt");
FileWriter _filewr = new FileWriter(_output);
BufferedWriter _buffwrt = new BufferedWriter(_filewr);
FileInputStream f = new FileInputStream(
"C:\\Users\\Diana\\Desktop\\FileTest\\test.txt.txt");
BufferedReader _buffer = new BufferedReader(new InputStreamReader(f));
String _str = _buffer.readLine();
while (_str != null) {
String[] _vect = _str.split(" ");
int i;
for (i = 0; i < _vect.length; i++) {
if (_vect[i].contains(".")) {
_buffwrt.write(_vect[i] + " ");
break;
}
else
_buffwrt.write(_vect[i] + " ");
_buffwrt.flush();
}
_str = _buffer.readLine();
}
}
public static void main(String[] args) throws Throwable {
readFile();
}
}
use another _buffwrt.flush(); outside the loop to flush anything remaining and don't forget _buffwrt.close(); at the end
update
#Svetlin Zarev mention a good point that only _buffwrt.close(); at the end will be sufficient to flush anything remaining
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close%28%29
The basic answer is, the break statement is breaking out of the loop, which is what you want, but it's also skipping the _buffwrt.flush(); statement. Because you're not closing the output streams correctly, the buffered content is simply been discard.
While you could put more flush statements in, it kind of defeats the purpose of BufferedWriter, instead, you should simply manage you resources better and make sure that they are getting closed when you are done with them, which will, in this case, flush the buffers before closing the resource.
File _output = new File("output.txt");
try (BufferedWriter _buffwrt = new BufferedWriter(new FileWriter(_output))) {
try (BufferedReader _buffer = new BufferedReader(new FileReader("test.txt"))) {
String _str = _buffer.readLine();
while (_str != null) {
String[] _vect = _str.split(" ");
int i;
for (i = 0; i < _vect.length; i++) {
if (_vect[i].contains(".")) {
System.out.println("1 " + _vect[i]);
_buffwrt.write(_vect[i] + " ");
break;
} else {
System.out.println("2 " + _vect[i]);
_buffwrt.write(_vect[i] + " ");
}
}
_str = _buffer.readLine();
}
}
} catch (IOException exp) {
exp.printStackTrace();
}
Take a look at The try-with-resources Statement for more details
I am coding a class that compares the files of two directories via comparing the Byte arrays of each file. I am however not getting the expected results; identical files are not being resolved as identical files.
First problem:
Matching the files Byte[] with equals() resolves to false with matching files (Checked with only one file as to circumvent the possible index misalignment issue; the check still resolves to false.).
Second problem:
When using Vector's containsAll() for checking that both Vectors of Byte[] match (One Vector per directory with Byte[] for each file) this check results in false even with identical directories (This check has been removed from the code below.). So is there an issue with the way I am aligning the two vectors? (I have checked this with using two directories with matching files in the same order loaded into matching indeces; this still results in a Vector mismatch).
Third problem:
When there are subdirectories in the directories being checked a file not found exception is thrown stating that access is denied. Why is this happening? How can I circumvent this? I do not want to check the files contained within the subdirectories, but I am designing the code so that the end user need not worry about the subdirectories of the directories being compared. This only happens when there are subdirectories, it work fine when there are no subdirectories in the directories being checked.
Example Exception:
Byte reading error!
Byte reading error!
java.io.FileNotFoundException: C:\Dir1\Dir2\Dir3\Dir4\SubDir (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at tools.filesystem.filecomparison.FileComparator.getBytes(FileComparator.java:166)
at tools.filesystem.filecomparison.FileComparator.main(FileComparator.java:102)
java.io.FileNotFoundException: C:\Dir1\Dir2\Dir3\Dir4\SubDir Files (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at tools.filesystem.filecomparison.FileComparator.getBytes(FileComparator.java:166)
at tools.filesystem.filecomparison.FileComparator.main(FileComparator.java:111)
Here is the code:
package tools.filesystem.filecomparison;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.Vector;
public class FileComparator
{
public static void main(String[] args)
{
String workingDir1 = "";
String workingDir2 = "";
File[] fileArr1 = null;
File[] fileArr2 = null;
Vector<File> fileVec1 = new Vector<File>();
Vector<File> fileVec2 = new Vector<File>();
Scanner console = new Scanner(System.in);
while (true)
{
System.out.println("Enter working directory one . . . .");
workingDir1 = console.nextLine();
workingDir1.replace("\\", "\\\\");
System.out.println("Enter working directory two . . . .");
workingDir2 = console.nextLine();
workingDir2.replace("\\", "\\\\");
File folder1 = new File(workingDir1);
File[] listOfFiles1 = folder1.listFiles();
File folder2 = new File(workingDir1);
File[] listOfFiles2 = folder2.listFiles();
fileArr1 = listOfFiles1;
fileArr2 = listOfFiles2;
System.out.println("\nWorking Directory 1 Files\n");
for (int i = 0; i < listOfFiles1.length; i++)
{
if (listOfFiles1[i].isFile())
{
System.out.println(" " + listOfFiles1[i].getName());
}
/* else if (listOfFiles1[i].isDirectory())
{
System.out.println("Directory " + listOfFiles1[i].getName());
}*/
}
System.out.println("\nWorking Directory 2 Files\n");
for (int i = 0; i < listOfFiles2.length; i++)
{
if (listOfFiles2[i].isFile())
{
System.out.println(" " + listOfFiles2[i].getName());
}
/* else if (listOfFiles2[i].isDirectory())
{
System.out.println("Directory " + listOfFiles2[i].getName());
}*/
}
for (File fle : fileArr1)
{
fileVec1.add(fle);
}
for (File fle : fileArr2)
{
fileVec2.add(fle);
}
if (fileVec1.containsAll(fileVec2))
break;
else
{
System.out.println("Directories do not contain the same files!\nContinue anyways? y/n?");
if (console.nextLine().equalsIgnoreCase("y"))
break;
else if (console.nextLine().equalsIgnoreCase("n"))
continue;
}
}
Vector<Vector<File>> alignedVectors = align(fileVec1, fileVec2);
fileVec1 = alignedVectors.elementAt(0);
fileVec2 = alignedVectors.elementAt(1);
Vector<byte[]> fileByteVect1 = new Vector<byte[]>();
Vector<byte[]> fileByteVect2 = new Vector<byte[]>();
try
{
fileByteVect1 = getBytes(fileVec1);
}
catch (IOException e)
{
System.out.println("Byte reading error!");
e.printStackTrace();
}
try
{
fileByteVect2 = getBytes(fileVec2);
}
catch (IOException e)
{
System.out.println("Byte reading error!");
e.printStackTrace();
}
boolean[] check = new boolean[fileByteVect1.capacity()];
int i1 = 0;
//debug
for (byte[] e : fileByteVect1)
{
System.out.println("Vector 1 count " + i1);
System.out.println(e.toString());
for (byte b : e)
{
System.out.print(b + " ");
}
i1++;
}
int i2 = 0;
//debug
for (byte[] e : fileByteVect2)
{
System.out.println("Vector 2 count " + i2);
System.out.println(e.toString());
for (byte b : e)
{
System.out.print(b + " ");
}
i2++;
}
if (fileByteVect1.size() == fileByteVect2.size())
{
System.out.println(fileByteVect1.size());
for (int i = 0; i < fileByteVect1.size(); i++ )
{
if (fileByteVect1.elementAt(i).equals(fileByteVect2.elementAt(i)))
{
check[i] = true;
System.out.println("File at index " + i + " are identical");
}
else
{
check[i] = false;
System.out.println("File at index " + i + " are not identical");
}
}
}
else
System.out.println("Files do not match!");
}
public static Vector<Vector<File>> align(Vector<File> fileVect1, Vector<File> fileVect2)
{
Vector<Vector<File>> mainBuffer = new Vector<Vector<File>>();
Vector<File> bufferFileVect = new Vector<File>();
for (File fle1 : fileVect1)
{
for (File fle2 : fileVect2)
{
if (fle1.getName().equals(fle2.getName()))
bufferFileVect.add(fle2);
}
}
mainBuffer.add(fileVect1);
mainBuffer.add(bufferFileVect);
return mainBuffer;
}
public static Vector<byte[]> getBytes(Vector<File> fileVector) throws IOException
{
Vector<byte[]> outVector = new Vector<byte[]>();
for (File file : fileVector)
{
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE)
{
System.out.println("File is too large!");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)
{
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length)
{
throw new IOException("Could not completely read file " + file.getName());
}
// Close the input stream and return bytes
outVector.add(bytes);
is.close();
}
return outVector;
}
}
The equals function isn't doing a deep comparison, rather for a byte[] you're comparing addresses. Instead you should use
Arrays.equals(fileByteVect1.elementAt(i), fileByteVect2.elementAt(i))
to perform the deep comparison of the byte arrays.
More detail on Arrays.equals.
As for your third question, you're not actually filtering for just files. When you iterate through to print out the filename you should construct the Vector storing the files:
for (File fle : fileArr1) {
if (fle.isFile()) {
fileVec1.add(fle);
System.out.println(" " + fle.getName());
}
}
You will, of course, have to do this for fileArr2 and fileVec2 as well.
Simple. The equals(Object) method on an array is inherited from Object, and hence is equivalent to the == operator; i.e. it is just a reference comparison.
This is specified in JLS 6.4.5.
If you want to compare arrays by value, use the java.util.Arrays.equals(array1, array2) methods. There are overloads for arrays of each primitive type and arrays of Object.
(Note that it is the semantics of each element type's implementation of equals method that determines if Arrays.equals(Object[], Object[]) is a "deep" or "shallow" comparison.)
FOLLOW UP
I suspect that the third problem happens because your application is trying to open the subdirectory as a file. That won't work. Instead, you need to:
Use File.isFile() and File.isDirectory() to determine whether you should be reading the directory entries as files or dirctories (or not at all).
For a directory, you should recursively use File.listFiles() or similar to iterate over the subdirectory contents.
So I have been working on a java project where the goal is to create a virtual computer. So I am basically done but with one problem. I have created a compiler which translates a txt document with assembly code in it and my compiler has created a new-file with this code written as machine executable ints. But now I need to write a load method that reads these ints and runs the program but I am having difficulty doing this. Any help is much appreciated....also this is not homework if you are thinking this. The project was simply to make a compiler and now I am trying to complete it for my own interest. Thanks.
Here is what I have so far for load:
public void load(String newfile) throws FileNotFoundException
{
try{
File file = new File(newfile);
FileInputStream fs = new FileInputStream(file);
DataInputStream dos = new DataInputStream(fs);
dos.readInt();
dos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Ok here is the part of the Compiler that does the writeInts:
public void SecondPass(SymbolList symbolTable, String filename){
try {
int dc = 99;
//Open file for reading
File file = new File(filename);
Scanner scan = new Scanner(file);
//Make filename of new executable file
String newfile = makeFilename(filename);
//Open Output Stream for writing new file.
FileOutputStream fs = new FileOutputStream(newfile);
DataOutputStream dos = new DataOutputStream(fs);
//Read First line. Split line by Spaces into linearray.
String line = scan.nextLine();
String[] linearray = line.split(" ");
while(line!=null){
if(!linearray[0].equals("REM")){
int inst = 0, opcode, loc;
if(isInstruction(linearray[0])){
opcode = getOpcode(linearray[0]);
loc = symbolTable.searchName(linearray[1]).getMemloc();
inst = (opcode*100)+loc;
} else if(!isInstruction(linearray[0])){
if(isInstruction(linearray[1])){
opcode = getOpcode(linearray[1]);
if(linearray[1].equals("STOP"))
inst=0000;
else {
loc = symbolTable.searchName(linearray[2]).getMemloc();
inst = (opcode*100)+loc;
}
}
if(linearray[1].equals("DC"))
dc--;
}
dos.writeInt(inst);
System.out.println(" inst is being written as:" + inst);
}
try{
line = scan.nextLine();
}
catch(NoSuchElementException e){
line = null;
break;
}
linearray = line.split(" ");
}
scan.close();
for(int i=lc; i<=dc; i++){
dos.writeInt(0);
}
for(int i = dc+1; i < 100; i++)
{
dos.writeInt(symbolTable.searchLocation(i).getValue());
}
dos.close();
fs.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So what I have done is write a file in txt like:
IN X
In Y
SUB X
STO Y
OUT Y
DC: X 0
DC: Y 0
And I wrote a compiler that has now converted this file into machine code so I have created a file for example called program.txt.ex and it contains a bunch of ####### or machine code and I did this using the SecondPass code above and now I need to write a load method that will allow me to load and run this file.
Here is my Run method
public void run(String filename) throws IOException
{
if (mem == null)
System.out.println("mem null");
if (filename == null)
System.out.println("filename null");
mem.loadFromFile(filename);
cpu.reset();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
while (!cpu.stop())
{
cpu.decode();
if (cpu.OutFlag())
OutPut.display(mem.read(cpu.getMAR()));
if (cpu.InFlag())
mem.write(cpu.getMDR(),in.getInt());
if (cpu.StoreFlag())
{
mem.write(cpu.getMAR(),in.getInt());
cpu.getMDR();
}
else
{
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.execute();
cpu.fetch();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
}
}
}
The Run Method:
public void run(int mem)
{
cpu.reset();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
while (!cpu.stop())
{
cpu.decode();
if (cpu.OutFlag())
OutPut.display(mem.read(cpu.getMAR()));
if (cpu.InFlag())
mem.write(cpu.getMDR(),in.getInt());
if (cpu.StoreFlag())
{
mem.write(cpu.getMAR(),in.getInt());
cpu.getMDR();
}
else
{
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.execute();
cpu.fetch();
cpu.setMDR(mem.read(cpu.getMAR()));
cpu.fetch2();
}
}
}
I notice that your loader does a single
dos.readInt();
...which will read a single integer value from your file. What you probably want to do is create a loop that reads ints until you hit the end-of-file on dos (which might more aptly be named dis, no?). You could add those ints to a dynamic container like an ArrayList, which will grow with every element you stuff into it. Once done loading, you can use toArray to copy all those ints to an array of the appropriate size.
If seems that you need to load the whole file in memory before starting execution, so it would go:
public int[] load(String newfile) throws FileNotFoundException
{
int mem[] = new int[100];
try {
File file = new File(newfile);
FileInputStream fs = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fs);
for (int i = 0; i < mem.length; ++i) {
mem[i] = dis.readInt();
}
dos.readInt();
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
return mem;
}
void run(int mem[]) {
// now execute code
int pc = 0;
loop: while (true) {
int inst = mem[pc++];
int opcode = inst/100;
int loc = inst%100;
switch (opcode) {
case OpCode.STOP:
break loop;
case OpCode.IN:
...
}
}
}