How does redirection in javac work? - javac

I am currently new with javaC. I have installed JDK and set the path to make it work. I have already done several test programs and they worked.
Let's say I have a java file called Read.java and a text file called Numbers.txt
I have already set my directory to where the files are and I enter to command
javac Read.java
then
java Read < input.txt
Problem is how I can set Read.java program to receive the input.txt file?
I know you can read the file from the program itself without redirection. But I want to learn how you can read a file using redirection.

Java's main method looks something like:
public static void main(String[] args)
{
// method body
}
args is an array of parameters that the user can pass to the program - the first parameter would be args[0], the second args[1] and so on.
To receive the input text file, you can have the user type java Read input.txt. input.txt will be the first parameter, and so you can access it by using args[0] in your main method.
A simple example of command line arguments:
public static void main(String[] args)
{
String input = args[0];
System.out.println("You entered: " + input);
}
You can run this by typing java ProgramName hello, and the output will be You entered hello.

You need to read from standard input:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IORedirection {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line = in.readLine()) != null){
System.out.println(line);
}
}
}
> echo "hello stdin" | java IORedirection
> hello stdin

how I can set Read.java program to receive the input.txt file? I know you can read the file from the program itself without redirection. But I want to learn how you can read a file using redirection.
There are several ways to get input to your program.
This isn't about "Java", but rather what are the ways for the caller to write data to "standard input" (or "stdin"). Within any Java program, you can read stdin with System.in.
So, use System.in within your program, and then use a pipe (|) or a redirect (<). Below are two working examples from an answer I posted on a related question:
% cat input.txt | java SystemInExample.java
% java SystemInExample.java < input.txt

Related

Dart How to load file in runtime

I'm writing a discord bot using the nyxx library and want use dynamic file import for load command info and handler. But, after 5 hours of searching with Google, I didn't find anything to help me do that.
In Node.js, I can use require() or import() for it: Does the dart have something like that?
A small code snippet, showing what I want do:
this.commands = new Collection();
fs.readdirSync('./src/commands').filter(( f ) => f.endsWith( '.js' )).forEach((file) => {
const command = require(`../commands/${file}`);
this.commands.set( command.info.name, command );
});
Is it possible to do this or not? (I don't like to write many imports for commands and register it in lib.)
You can in theory use Isolate.spawnUri to spawn external Dart programs to run in its own Isolate instances that can then communicate back to the main program using SendPort.
It does, however, come with some limitations. E.g. it is very limited what types of objects you can send though SendPort when using spawnUri since the two programs does not share any type information (compared to Isolate.spawn which does allow you to send your own custom types). The documented types you can send can be found here:
Null
bool
int
double
String
List or Map (whose elements are any of these)
TransferableTypedData
SendPort
Capability
https://api.dart.dev/stable/2.17.6/dart-isolate/SendPort/send.html
But it does allow us to make some kind of protocol and you can create some helper class around this to handle the conversion of a known object structure into e.g. Map<String, Object>.
A small example that works with Dart VM would be:
Your command implemented as: command.dart
import 'dart:isolate';
void main(List<String> arguments, Map<String, Object> message) {
final userName = message['username'] as String;
final sendPort = message['port'] as SendPort;
sendPort.send('Hi $userName. '
'You got a message from my external command program!');
}
Your server that calls your command: server.dart
import 'dart:isolate';
void main() {
final recievePort = ReceivePort();
recievePort.listen((message) {
print('Got the following message: $message');
recievePort.close();
});
Isolate.spawnUri(Uri.file('command.dart'), [], {
'username': 'julemand101',
'port': recievePort.sendPort,
});
}
If running this with: dart server.dart you, hopefully, get:
Got the following message: Hi julemand101. You got a message from my external command program!
If you want to compile your application, you can do so by doing the following. You need to compile the command.dart, since a compiled Dart program does not understand how to read Dart code.
dart compile exe server.dart
dart compile aot-snapshot command.dart
You should here change Uri.file('command.dart') to Uri.file('command.aot') since the file-extension for aot-snapshot are .aot.
If everything works, you should be able to see:
> .\server.exe
Got the following message: Hi julemand101. You got a message from my external command program!

How to run AwReporting in Eclipse?

I am getting Error
ERROR|com.google.api.ads.adwords.awreporting.AwReporting|AwReporting] Missing required option: 'file'
When I try to run AwReporting.java
You have to provide some information as command line argument to the program for it to run (-file, -startDate, -endDate).
Solution 1:
Right click the inside the AwReporting.java in eclipe, go to Run
As->Run Configuration.
Click Arguments tab and add the following in the Program Arguments box
-file adword property file location -startDate start date -endDate end date
Example:
-file src/main/resources/aw-report-sample.properties -startDate 20160126 -endDate 20160127
Solution 2:
You can replace the args variable by the below code in the first line on the main() function on AwReporting.java.
args = new String[] {"-file","<adword property file location>","-startDate","<YYYYMMDD>","-endDate","<YYYYMMDD>"};
Example:
public static void main(String args[])
{
args = new String[] {"-file","src/main/resources/aw-report-sample.properties","-startDate","20160126","-endDate","20160127"};

How to change macro escape char in Apache Velocity

I'm using apache velocity in front of LaTeX. The # and $ escape chars are conflicting with LaTeX. I want to replace # with %% and $ with ## to avoid the conflicts. Simply using a string replace on the source file code is not a good solution because I have to use things like #parse and #include. The parsed/included file should also be able to use the modified escape chars. Is there a way to configure this? Is there a configuration option?
You can use a custom resource loader to modify files loaded by #parse:
VelocityEngine engine = new VelocityEngine();
Properties props = new Properties();
props.put("resource.loader", "customloader");
props.put("customloader.resource.loader.class", CustomLoader.class.getName());
engine.init(props);
public static class CustomLoader extends FileResourceLoader {
public InputStream getResourceStream(String arg0) throws ResourceNotFoundException {
InputStream original = super.getResourceStream(arg0);
//TODO modify original, return modified
original.close();
}
}

Code cannot find a line on a website

I've been trying to find a line and print it out on this website: http://www.easports.com/player-hub/360/Its+McDoom
Right now it prints out everything on the website, but I cannot find the line I am looking for. I am trying to print out "H2h Skill Points: 1053", but I cannot find anything like that in the console.
I only really want it to print that 1 line, not the whole thing, but I can't even find it.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class ElectronicArtsStatHub {
/**
* #param args
*/
public static void main (String[] args) throws Exception{
URL oracle = new URL("http://www.easports.com/player-hub/360/Its+McDoom");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
The first problem is that the information your trying to find isn't actually in the data you are currently outputting.
When you open the page in your browser you get the main page elements but then your browser then runs some Javascript code which presumably uses AJAX to get the stats and fill in the table.
The URLConnection receives the same data that your browser initially does and does not execute the Javascript so if you check your output that data your looking for isn't actually there at all.
Possible solutions include finding a different source for this data or executing the Javascript in Java possibly by using HTMLUnit
There may be some helpful infomation on this related question

How to generate an HTML report from PartCover results .xml

How to generate an HTML report from PartCover results .xml
There is a tool you can use to generate a HTML report:
https://github.com/danielpalme/ReportGenerator
Here you can find an article how to integrate the tool into MSBuild:
http://www.palmmedia.de/Blog/2009/10/30/msbuild-code-coverage-analysis-with-partcover-and-reportgenerator
To my knowledge, there is no convenient tool like NCoverExplorer that can transform a PartCover results .xml file into a .html report, but there are some .xsl files that can be used to transform PartCover's results to .html in CruiseControl.NET: Using CruiseControl.NET with PartCover.
You could take those .xsl files from CruiseControl.NET and convert your PartCover results.xml using something like Sandcastle's XslTransform.exe.
By the way, if this happens to be related to TeamCity, the upcoming 5.0 release will include support for .NET coverage using PartCover or NCover. See the documentation for more informations. Otherwise ignore this paragraph ;-)
Easiest solution is probably to use msxsl, a simple command line transformer. I use it for exactly this purpose, and it's easy to integrate into your build system.
http://www.microsoft.com/downloads/details.aspx?FamilyID=2FB55371-C94E-4373-B0E9-DB4816552E41&displaylang=en
Maybe a complicated way of doing it, but I did this with the Simian xml report. Created an XSL file for the formatting, then wrote a dumb little console application;
private const string MissingExtension = "Please enter a valid {0} file, this is missing the extension.";
private const string InvalidExtension = "Please enter a valid {0} file, the file provided has an invalid extension.";
public static void Main(string[] args)
{
if (args.Length < 2)
{
System.Console.WriteLine("Please enter a xsl file and xml file full path.");
return;
}
var xslFile = args[0];
var xmlFile = args[1];
if (!CheckFileNameFormat(xslFile, false))
return;
if (!CheckFileNameFormat(xmlFile, true))
return;
var transform = new XslCompiledTransform();
// Load the XSL stylesheet.
transform.Load(xslFile);
// Transform xml file into an html using the xsl file provided.
transform.Transform(xmlFile, xmlFile.Replace("xml", "html"));
}
private static bool CheckFileNameFormat(string fileName, bool isXmlFile)
{
var extension = isXmlFile ? "xml" : "xsl";
// valida that the argument has a period
if (fileName.IndexOf(".") < 1)
{
System.Console.WriteLine(string.Format(MissingExtension, extension));
return false;
}
var filePieces = fileName.Split('.');
// split on the period and make sure the extension is valid
if (filePieces[filePieces.GetUpperBound(0)] != extension)
{
System.Console.WriteLine(string.Format(InvalidExtension, extension));
return false;
}
return true;
}
Then I can call it from a MSBuild file like so;
<Target Name="RunSimian" DependsOnTargets="RebuildSolution">
<Exec IgnoreExitCode="true" Command=""$(MSBuildProjectDirectory)\..\Build\Packages\Simian\simian-2.2.24.exe" -formatter=xml:$(MSBuildProjectDirectory)\..\Build\Artifacts\simian.xml -language=cs -excludes=$(MSBuildProjectDirectory)\..\Product\Production\**\*.Designer.cs $(MSBuildProjectDirectory)\Production\**\*.cs" >
</Exec>
<Exec IgnoreExitCode="true" Command=""$(MSBuildProjectDirectory)\..\Build\Packages\XmlToHtmlConverter.exe" $(MSBuildProjectDirectory)\..\Build\Packages\Simian\simian.xsl $(MSBuildProjectDirectory)\..\Build\Artifacts\simian.xml">
</Exec>

Resources