I am learning Java through an introductory course using the textbook, Java Programming 9th Edition by Joyce Farrel. The examples and exercises are written for Java 9e, however, I am using Java SE 14.
I've successfully navigated Java API and found updates as well as useful explanations as to what errors I have been encountering between the two versions and what is the best way to make corrections to get the examples and exercises to work.
However, in this case, I have been having a really hard time. I'm pretty sure it's due to the lack of experience, but I can't find anything I can understand using the Java API that has given me an idea on how to resolve this issue. Google and Stackoverflow posts have not been that much more successful as I am assuming people are using a much more streamlined method or approach.
Code with the comment on the line in question:
...
Path rafTest = Paths.get("raf.txt");
String addIn = "abc";
byte[] data = addIn.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);
FileChannel fc = null;
try {
fc = (FileChannel)Files.newByteChannel(file, READ, WRITE); // Error READ and Write is ambiguous?
...
} catch (Exception e){
System.out.println("Error message: " + e);
}
...
What is the best way to go about finding an approach to figuring out what exactly is going here?
#Bradley: Found the answer by trying to rewrite my question. The compiler returned 3 specific errors dealing with StandardOpenOption. Using that and Java API, I found the solution. Thank you.
#NomadMaker: First thought was that I did not include the package correctly for newByteChannel. The second options were that the arguments needed a more specific reference.
Answer: newByteChannel(...); requires the open options argument to reference the StandardOpenOption.READ and WRITE. So that:
...newByteChannel(raf, StandardOpenOption.READ, StandardOpenOption.WRITE);
This change was implemented in Java SE 11. The program now works correctly.
Related
Attempting to re-write the Minecraft Launcher in jython as i have a rather basic knowledge of java but i believe im competent enough with python to undertake this task. I've been translating the decompiled classes as best as i can, but i'm encountering this SyntaxError whenever i try to append strings to my list launchParameters.
The reason why i'm puzzled as to why this is happening is because the first .append() worked for my list, but after that i get the mentioned SyntaxError thrown at me from the console.
#classmethod
def main(cls, paramArrayofString):
maxHeap = 1024
minHeap = 511
runtimeMemory = float(Runtime.getRuntime().maxMemory() / maxHeap / maxHeap)
if (runtimeMemory > minHeap):
LauncherFrame.main(paramArrayofString)
else:
try:
someString = CraftiLauncher.__class__.getProtectionDomain().getCodeSource().toURI().getPath()
launchParameters = []
if (Util.getPlatform() == "Windows"):
launchParameters.append("javaw")
else:
launchParameters.append("java")
launchParameters.append("-Xmx1024m") #This one appears to work
launchParameters.append("-Dsun.java2d.noddraw=true") #This is where i get my first error
launchParameters.append("-Dsun.java2d.d3d=false")
launchParameters.append("-Dsun.java2d.opengl=false")
launchParameters.append("-Dsun.java2d.pmoffscreen=false")
launchParameters.append("-classpath")
launchParameters.append(someString)
launchParameters.append("net.Crafti.LauncherFrame")
localProcessBuilder = ProcessBuilder(launchParameters)
localProcess = localProcessBuilder.start()
if (localProcess == None):
sys.exit()
if there's anything i need to elaborate on, please ask; if you think there's a page that might help me, feel free to link it!
Thanks in advance!
Well, i'm not entirely sure why i was getting the error, but it seems that just a simple fix of code indentation was the answer the whole time.
I didn't even change the indentation at all; i just simply dedented and indented everything again and now it works!
Would anyone please explain how(and what for) to use the TeeSinkTokenFilter, from Lucene? An example would be much appreciated too =P. I didn't find the official documentation much clear , and have also looked up many sites, without much progress.
Thanks.
Yeah, I didn't think the official documentation was very clear, either. I think part of what made it so confusing is that it demonstrated two different features together in a way that made it hard to tell them apart. Let me see if I can rewrite their example to just show the basic case.
TeeSinkTokenFilter source1 = new TeeSinkTokenFilter(
new WhitespaceTokenizer(version, reader1));
TeeSinkTokenFilter.SinkTokenStream sink1 = source1.newSinkTokenStream();
TeeSinkTokenFilter.SinkTokenStream sink2 = source1.newSinkTokenStream();
source1.consumeAllTokens(); // all tokens get cached at this point
TokenStream final3 = new EntityDetect(sink1);
TokenStream final4 = new URLDetect(sink2);
d.add(new TextField("f3", final3, Field.Store.NO));
d.add(new TextField("f4", final4, Field.Store.NO));
This allows the final3 and final4 token streams to share the processing done by source1. As the official documentation said, the order in which the streams are consumed is important, but as it doesn't say, the order appears to be indeterminate (or maybe alphabetical by field name). I recommend using the consumeAllTokens method as I've done above.
i would like to know whether exist a way to parallelize queries in Java (or there is framework or a library) like in C# and Linq:
var query = from item in source.AsParallel().WithDegreeOfParallelism(2)
where Compute(item) > 42
select item;
and if i can't parallelize queries if i can do something like this in c# (a for each parallelized) :
Parallel.ForEach(files, currentFile =>
{
// The more computational work you do here, the greater
// the speedup compared to a sequential foreach loop.
string filename = System.IO.Path.GetFileName(currentFile);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(currentFile);
bitmap.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
bitmap.Save(System.IO.Path.Combine(newDir, filename));
// Peek behind the scenes to see how work is parallelized.
// But be aware: Thread contention for the Console slows down parallel loops!!!
Console.WriteLine("Processing {0} on thread {1}", filename,
Thread.CurrentThread.ManagedThreadId);
}
please if you post any framework or library, can you tell me the experience that you had with it ?
thx for your time.
about c# and linq you can find here the documentation : http://msdn.microsoft.com/en-us/library/dd997425.aspx
There isn't a direct translation. Firstly Java doesn't have LINQ nor does it have any standard parallel collection classes.
GPars is perhaps closest fit.
Note that while it is targeted at groovy it's API is perfectly usable from java
Maybe Fork/Join Framework can help you ? Here is java tutorial
Actually I was searching for an example or similar question in Stackoverflow and I find this one : Java Objective-C for each issue. So that's why I'll give the code which Android-Droid is using in his example.The thing that I need to do is similar to the Objective C code that he is using :
StPacketInjectQueryPackage qType = (StPacketInjectQueryPackage)[[q objectForKey:#"type"] intValue]; .
According to his code...my question is how can I do that...using his Java code?
EDIT (My Problem):
If I use his code, how can I get the objectForKey:#"type" in Java.I guess it has to be similar to this :
RPCPacketInjectQueryPackage qType = (RPCPacketInjectQueryPackage) b.getKeys
OR b.get("type"); or something like that...
Any suggestions?
For-each in Java is pretty well documented in the standard Java documentation. For example: http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html
If that doesn't adequately explain how to do what you're trying to do, I would suggest taking a stab at it in Java and then asking a question on StackOverflow about what is wrong with your code if you can't get it to work.
The closest thing in Java is a new (1.5 or 1.6) "enhanced" for loop.
Iterable<Element> list = ....
for (Element el : list) {
System.out.println(el);
}
I am currently using an online system running in Google App Engine to enable students to practice coding in python. The system is inspired by codingbat by Nick Parlante and the public version of Beanshell running on appengine.
I would like to extend our system to support Java. In our current system, the Python doctest feature makes it very easy for instructors to type out a series of variable declarations and doctests which can then be executed against student-submitted code. It is very intuitive for the instructors which is important to ensure lots of people are writing tests.
How do I replace the following comments with Java code to eval and execute tests in Java?
String solution = “a=1;”;
solution += “b=1;”;
String problem = “self.assertEqual(a,1);”;
problem += “c=3;”;
problem += “self.assertEqual(b,2);”;
//eval the solution string
//eval the problem string possibly wrapped by additional junit or other Java code.
//results = Run all the tests
System.out.println(“Test expected received result”);
//For result in results
// print test, expected, received, result(pass/fail)
Desired output:
Test expected received result
self.assertEqual(a,1) 1 1 pass
self.assertEqual(b,2) 2 1 fail
Ideally any number of tests could be included in the problem string above and any number of Java statements could be included in the solution string in order to pass the tests included in the problem string.
To the best of my knowledge, you can't. Compiling Java code at runtime requires access to APIs that aren't available on App Engine; that's why things like BeanShell and LOTRepls don't support Java.