// JGrep.cpp // Definition of main class for NewJ application // From the NewJ Library for C++ Developer's Guide, // chapter 7, "Getting Started: Your First NewJ Application" // Include declaration of main class first #include "JGrep.h" // TODO: include declarations of referenced classes #include #include #include #include #include using namespace ::java::lang; using ::java::io::RandomAccessFile; // the class type using ::java::io::RandomAccessFileR; // the reference type using ::java::io::FileNotFoundException; // the class type using ::java::io::FileNotFoundExceptionR; // the reference type using ::java::io::IOException; // the class type using ::java::io::IOExceptionR; // the reference type // This causes your main class to define a Class object for itself, // so its main method may be called dynamically at run-time and // it itself may be dynamically instantiated at run-time. // TODO: change this to PIE_DEFINE_MAIN_CLASS_METHOD_ONLY() if // public default constructor is removed from this class PIE_DEFINE_MAIN_CLASS(JGrep, "JGrep"); // TODO: add using statements to make working with namespace easier. // In the following a class name is imported, but not its reference // type or its array reference types. To import all of these, use // the pi_importclass abstract keyword instead. For example, // pi_importclass(::java::lang::System); // To import an entire namespace, use something like the following: // using namespace ::java::lang; using ::java::lang::System; JGrep::JGrep() { // TODO: implement constructor } JGrep::~JGrep() { // TODO: implement destructor } // NewJ equivalent of 'void main(String[] args)'. // Note that StringAR is a reference to an array of String objects. // A stands for array, and R stands for reference. void JGrep::main(::java::lang::StringAR args) { if (args->length_ != 2) { System::out_->println(PI_T("usage: JGrep filename searchpattern")); System::exit(0); } doGrep(args[0], args[1]); } void JGrep::doGrep(::java::lang::StringR fileName, ::java::lang::StringR searchPattern) { try { RandomAccessFileR file = pi_new(RandomAccessFile, RandomAccessFile(fileName, PI_T("r"))); pi_int lineNumber = 1; for ( ; ; ) // loop forever { StringR line = file->readLine(); if (line == pi_null) { break; } if (line->indexOf(searchPattern) != -1) { System::out_->println(lineNumber + PI_T(": ") + line); } lineNumber ++; } file->close(); } catch (FileNotFoundExceptionR& exception) { System::out_->println(PI_T("Unable to open file '") + fileName + PI_C('\'')); } catch (IOException& exception) { System::out_->println(PI_T("Unexpected read error occurred")); } }