Syntax error on token "Invalid Character", delete this token - java

I am not sure why is it giving this error. Braces seem to be right. Another thing is that the same program works in Windows-eclipse but not in eclipse for Mac. What could be the reason?
import java.util.Vector;
public class Debug
{
private int something = 0;
private Vector list = new Vector();
public void firstMethod()
{
thirdMethod(something);
something = something + 1;
}
public void secondMethod()
{
thirdMethod(something);
something = something + 2;
}
public void thirdMethod(int value)
{
something = something + value;
}
public static void main(String[] args)
{
Debug debug = new Debug();
debug.firstMethod();
debug.secondMethod();
}
}

Ah, ok - it's probably a control-Z or other unprintable character at the end of the file that is ignored in Windows but not on the Mac. You copied the source from Windows to the Mac. Delete the last few characters and re-enter them - I think it will go away. I don't do Mac, though - I'm just guessing.

I had the same problem importing my projects from mac to linux Slackware.
Mac OSX creates some temporary files with the same name of the files in folders (._filename) in all folders.
Usually these files are invisible in Mac OSX, but in the other OSs no.
Eclipse can find these files and tries to handle like sources (._filename.java).
I solved deleting these files.

Only way i could resolve this problem was press Ctrl+A to select all text of file then Ctrl+C to copy them then delete file and create new class with intellij idea then Ctrl+P to paste text in new file. this resolve my problem and compiler never show error after do this solution.

It can happen when we copy and paste .It happens when there may be some character which is unrecognized in one platform but recognized in other.
I would suggest don't copy rather try to write the entire code by yourself. It should work

I got the same error when I imported a project I created in a Mac, to Windows. As #Massimo says Mac creates ._filename,java files which eclipse running in windows consider as source files. This is what causes the problem.
They are hidden files, which you can see when you select the option, "Show hidden files and folders" under folder options in Windows machine. Deleting these files solves the problem.

I got this message trying to call a subjob from a tRunJob component. In the tRunJob I had both checked "transmit whole context" AND listed individual parameters in the parameters/values box. Once I removed the additional parameters it worked.

There are probably hidden characters in the line. If you move your cursor through the characters and your cursor doesn't move in one character, that means there is an invalid character in the line. Delete those and it should work. Also try copying and pasting the line to an hex editor and you will see the invalid characters in it.

i face this problem many times in eclipse . What i found is that select all code - cut it using Ctrl + x and then save the file and again paste the code using Ctrl + V . This works for me many times when i copy the code from another editor.

I also faced similar issue while copying the code from one machine to another.
The issue was with Space only you need to identify the red mark in your eclipse code.

On Windows, if you copy the source to Notepad - save the file (as anything), ensuring ASCI encoding is selected - the character will be converted to a question-mark which you can then delete - then copy the code back to Eclipse.

In eclipse right click on the file -> Properties -> resources
In Text file encoding select US-ASCII
This way you will see all the special char, you can then find & replace
And then format the code

Related

Logging files names that contain Norwegian letters in the file name in Unix OS using a Jar executable

I have a simple java program that when run is supposed to traverse through the whole directory on a Unix server and log all files on the fileserver that contain Norwegian letters "å,ø,æ".
This is how it looks on the fileserver using winSCP:
In the end the logs.log file should look like this:
2022-10-25 14:27:02 INFO Logger:99 - File: 'DN_Oppmålings.pdf'
2022-10-25 14:27:02 INFO Logger:99 - File: 'Salg_av_gærden.pdf'
However, this is how it ends up in the log file, all Norwegian letters are represented with a square.
I can't seem to figure out why it happens. It probably has something to do with the encodings. Because when I run it on windows locally, everything runs as expected and I get the result I need. But when I build the project as an executable jar and run on the server it gets wrong.
Here is the code I am using.
public static void renameFiles3(File[] files) throws IOException {
for (File filename : files) {
if (filename.isDirectory()) {
renameFiles3(filename.listFiles());
} else {
String fileNameString = filename.getName();
if (fileNameString.contains("å") || fileNameString.contains("ø") || fileNameString.contains("æ")){
logger.info("File: '" + filename.getName());
}
}
}
}
public static void main(String[] args) {
File[] files = new File(path).listFiles();
try {
renamer.renameFiles3(files);
} catch catch(IOException ex){
logger.error(ex.toString());
}
}
Someone pointed out that the encoding should be specified, but I am not sure how that is done. If I run "locale" command on the Unix server this is what I get as output.
[e1111111#ilt repository]$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
I use Putty to run the jar file. Here are the configs.
Stacktrace of the error I get when running the jar:
java.nio.file.NoSuchFileException: ./documentRepository/DN_Oppm�lings.pdf
at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
at java.base/sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:430)
at java.base/sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:267)
at java.base/java.nio.file.Files.move(Files.java:1422)
at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:105)
at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
at com.example.fixfilenamesonfileserver.Renamer.main(Renamer.java:154)
What makes it even more strange, is that I can create for instance a folder with mkdir containing Norwegian letters in the name and it would be displayed correctly and also logged correctly if I create a file with Norwegian letters.
Some time ago I wrote an answer for a very similar problem.
As stated in the aforementioned solution, the problem could be related with the use of different charsets in your local Windows laptop (probably, cp-1252 or some variant) and your server.
As suggested, please, consider review the charset which is in place in the JVM in every environment, and review and adapt if necessary the value of the file.encoding system property on your laptop and the server environment, maybe it will help you solve the problem.
Probably running your jar with a proper value for the file.encoding JVM property may do the application work properly:
java -Dfile.encoding=UTF-8 -jar your_app.jar
I suspect there is no problem with your Java nor your file.
The problem is likely with the app you use to view that text. That app is using a font that lacks a glyph for those characters.
Edit your Question to note the app and OS if you want further assistance.
Assuming you are printing the letters to a terminal, the problem is most likely the terminal you use. If you are printing the characters to a terminal, make sure it is set to chcp65001, and a font that supports displaying norwegian letters fully. I have encountered similar problems while trying to display multilingual text due to the shortage of support for multiple languages in the same font.
So, to summarize, first set the terminal code-page encoding to chcp 65001, and then change the font of the terminal to a font that supports norwegian letter fully, and then run the jar file from the terminal like : java -jar <jarname>.jar

im trying to create a thread that sends and receives a message in java however im unsure on how to solve the error messages that are displayed [duplicate]

I have been working on an assignment for my class in programming. I am working with NetBeans. I finished my project and it worked fine. I am getting a message that says "No main class found" when I try to run it. Here is some of the code with the main:
package luisrp3;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
I posted this before but had a couple issues. i have fixed the others and now have just this one remaining. Any advice will be greatly appreciated.
Right click on your Project in the project explorer
Click on properties
Click on Run
Make sure your Main Class is the one you want to be the entry point. (Make sure to use the fully qualified name i.e. mypackage.MyClass)
Click OK.
Run Project :)
If you just want to run the file, right click on the class from the package explorer, and click Run File, or (Alt + R, F), or (Shift + F6)
Also, for others out there with a slightly different problem where Netbeans will not find the class when you want when doing a browse from "main classes dialog window".
It could be that your main method does have the proper signature. In my case I forgot the args.
example:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above.
Args: You can name the argument anything you want, but most programmers choose "args" or "argv".
Read more here:
http://docs.oracle.com/javase/tutorial/getStarted/application/
When creating a new project - Maven - Java application in Netbeans
the IDE is not recognizing the Main class on 1st class entry. (in Step 8 below we see no classes).
When first a generic class is created and then the Main class is created Netbeans is registering the Main class and the app could be run and debugged.
Steps that worked for me:
Create new project - Maven - Java application
(project created: mytest; package created: com.me.test)
Right-click package: com.me.test
New > Java Class > Named it 'Whatever' you want
Right-click package: com.me.test
New > Java Main Class > named it: 'Main' (must be 'Main')
Right click on Project mytest
Click on Properties
Click on Run > next to 'Main Class' text box: > Browse
You should see: com.me.test.Main
Select it and click "Select Main Class"
Hope this works for others as well.
The connections I made in preparing this for posting really cleared it up for me, once and for all. It's not completely obvious what goes in the Main Class: box until you see the connections. (Note that the class containing the main method need not necessarily be named Main but the main method can have no other name.)
I had the same problem in Eclipse, so maybe what I did to resolve it can help you.
In the project properties I had to set the launch configurations to the file that contains the main-method (I don't know why it wasn't set to the right file automatically).
In project properties, under the run tab, specify your main class.
Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.
If the advice to add the closing braces work, I suggest adding indentation to your code so every closing brace is on a spaced separately, i.e.:
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
// stuff
}
}
This just helps with readability.
If, on the other hand, you just forgot to copy the closing braces in your code, or the above suggestion doesn't work: open up the configuration and see if you can manually set the main class. I'm afraid I haven't used NetBeans much, so I can't help you with where that option is. My best guess is under "Run Configuration", or something like that.
Edit: See peeskillet's answer if adding closing braces doesn't work.
There could be a couple of things going wrong in this situation (assuming that you had code after your example and didn't just leave your code unbracketed).
First off, if you are running your entire project and not just the current file, make sure your project is the main project and the main class of the project is set to the correct file.
Otherwise, I have seen classmates with their code being fine but they still had this same problem. Sometimes, in Netbeans, a simple fix is to:
Copy your current code (or back it up in a different location)
Delete your current file
Create a new main class in your project (you can name it the old one)
Paste your code back in
If this doesn't work then try to clear the Netbeans cache, and if all else fails, then just do a clean un-installation and re-installation of Netbeans.
In the toolbar search for press the arrow and select Customize...
It will open project properties.In the categories select RUN.
Look for Main Class.
Clear all the Main Class character and type your class name.
Click on OK.
And run again.
The problem is solved.
If that is all your code, you forgot to close the main method.
Everything else looks good to me.
public class LuisRp3 {
public static void main(String[] args) throws FileNotFoundException {
java.io.File newFile = new java.io.File("LuisRamosp4.txt");
if (newFile.exists()) {
newFile.delete();
}
System.setOut(new PrintStream(newFile));
Guitar guitar = new Guitar();
}}
Try that.
You need to add }} to the end of your code.
You need to rename your main class to Main, it cannot be anything else.
It does not matter how many files as packages and classes you create, you must name your main class Main.
That's all.
import java.util.Scanner;
public class FarenheitToCelsius{
public static void main(String[]args){
Scanner input= new Scanner(System.in);
System.out.println("Enter Degree in Farenheit:");
double Farenheit=input.nextDouble();
//convert farenheit to celsius
double celsuis=(5.0/9)*(farenheit 32);
system.out.println("Farenheit"+farenheit+"is"+celsius+"in celsius")
{
I also experienced Netbeans complaining to me about "No main classes found". The issue was on a project I knew worked in the past, but failed when I tried it on another pc.
My specific failure reasons probably differ from the OP, but I'll still share what I learnt on the debugging journey, in-case these insights help anybody figure out their own unique issues relating to this topic.
What I learnt is that upon starting NetBeans, it should perform a step called "Scanning projects..."
Prior to this phase, you should notice that any .java file you have with a main() method within it will show up in the 'Projects' pane with its icon looking like this (no arrow):
After this scanning phase finishes, if a main() method was discovered within the file, that file's icon will change to this (with arrow):
So on my system, it appeared this "Scanning projects..." step was failing, and instead would be stuck on an "Opening Projects" step.
I also noticed a little red icon in the bottom-right corner which hinted at the issue ailing me:
Unexpected Exception
java.lang.ExceptionInInitializerError
Clicking on that link showed me more details of the error:
java.security.NoSuchAlgorithmException: MD5 MessageDigest not available
at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
at java.security.Security.getImpl(Security.java:695)
at java.security.MessageDigest.getInstance(MessageDigest.java:167)
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:113)
Caused: java.lang.RuntimeException
at org.apache.lucene.store.FSDirectory.<clinit>(FSDirectory.java:115)
Caused: java.lang.ExceptionInInitializerError
at org.netbeans.modules.parsing.lucene.LuceneIndex$DirCache.createFSDirectory(LuceneIndex.java:839)
That mention of "java.security" reminded me that I had fiddled with this machine's "java.security" file (to be specific, I was performing Salvador Valencia's steps from this thread, but did it incorrectly and broke "java.security" in the process :))
Once I repaired the damage I caused to my "java.security" file, NetBeans' "Scanning projects..." step started to work again, the little green arrows appeared on my files once more and I no longer got that "No main classes found" issue.
Had the same problem after opening a project that I had downloaded in NetBeans.
What worked for me is to right-click on the project in the Projects pane, then selecting Clean and Build from the drop-down menu.
After doing that I ran the project and it worked.
Make sure the access modifier is public and not private. I keep having this problem and always that's my issue.
public static void main(String[] args)

Make JAR as a standalone executable

Is there a way to convert JAR lib into JAR standalone?
I need to find a standalone java executable that convert PDF into TIFF and I've found these JARs: http://www.icefaces.org/JForum/posts/list/17504.page
Any ideas?
Easiest might be to create another Jar with a Main() entry point, and then just use the java.exe executable to run it:
e.g.
> java.exe -cp MyJarMain.jar;MyPDFJar.jar com.mydomain.MyMain myPDF.pdf
Where MyMain is a class with a Main static method.
You'll need something with a main entry point to pass in and interpret some command line arguments (myPDF.pdf in my made-up example)
You could do an assembly (are you using maven?) and make sure the Main-Class entry in the manifest.mf points to the main class.
Since there is no main-Method, you have to write one, or write a whole new class to call the class/method TiffConver.convertPDF .
The question is, how you're going to use it. From the command line, you need no executable jar. From the Gui, maybe you want to pass a file to be converted by drag and drop? Then you should take the parameter(s) passed to main as Input-PDF-Names (if they end in .pdf) and pass the names iteratively to TiffConverter, for "a.pdf b.pdf" =>
TiffConver.convertPDF ("a.pdf", "a.tiff");
TiffConver.convertPDF ("b.pdf", "b.tiff");
TiffCoverter will silently overwrite existing tiffs, so check that before or change the code there - this is clearly bad habit, and look out for more such things - I didn't.
/*
* Remove target file if exists
*/
File f = new File(tif);
if (f.exists()) {
f.delete();
}
Maybe you wan't to write a swing-wrapper, which let's you choose Files interactively to be converted. This would be a nice idee, if no filename is given.
If the user passes "a.pdf xy.tiff" you could rename the converted file to xy, as additional feature.
Without a main-class, however, a standalone jar would be magic.
However, building a native executale is almost always a bad idea. You loose portability, you don't profit from security- and performance improvements to the JVM or fixed bugs. For multiple programs you need always an independend bugfix, which you might have to manage yourself, if you don't have a package-management as most linux distros have.
after clearing some questions:
public static void main (String [] args) {
if (args.length == 1 && args[0].endsWith (".pdf")) {
String target = args[0].replaceAll (".pdf$", ".tif");
convertPDF (args[0], target);
}
}
This method you put into TiffConvert. It will allow you to convert a simple pdf-File, and generate a tif-File with the same basename but ending in .tif, silently overwriting an existing one of the same name.
I guess you now need to know how to start it?

How can I make OS X recognize drive letters?

I know. Heresy. But I'm in a bind. I have a lot of config files that use absolute path names, which creates an incompatibility between OS X and Windows. If I can get OS X (which I'm betting is the more flexible of the two) to recognize Q:/foo/bar/bim.properties as a valid absolute file name, it'll save me days of work spelunking through stack traces and config files.
In the end, I need this bit of Java test code to print "SUCCESS!" when it runs:
import java.io.*;
class DriveLetterTest {
static public void main(String... args) {
File f = new File("S:");
if (f.isDirectory()) {
System.out.println("SUCCESS!");
} else {
System.out.println("FAIL!");
}
}
}
Anyone know how this can be done?
UPDATE: Thanks for all the feedback, everyone. It's now obvious to me I really should have been clearer in my question.
Both the config files and the code that uses them belong to a third-party package I cannot change. (Well, I can change them, but that means incurring an ongoing maintenance load, which I want to avoid if at all possible.)
I'm in complete agreement with all of you who are appalled by this state of affairs. But the fact remains: I can't change the third-party code, and I really want to avoid forking the config files.
Short answer: No.
Long answer: For Java you should use System.getProperties(XXX).
Then you can load a Properties file or Configuration based on what you find in os.name.
Alternate Solution just strip off the S: when you read the existing configuration files on non-Windows machines and replace them with the appropriate things.
Opinion: Personally I would bite the bullet and deal with the technical debt now, fix all the configuration files at build time when the deployment for OSX is built and be done with it.
public class WhichOS
{
public static void main(final String[] args)
{
System.out.format("System.getProperty(\"os.name\") = %s\n", System.getProperty("os.name"));
System.out.format("System.getProperty(\"os.arch\") = %s\n", System.getProperty("os.arch"));
System.out.format("System.getProperty(\"os.version\") = %s\n", System.getProperty("os.version"));
}
}
the output on my iMac is:
System.getProperty("os.name") = Mac OS X
System.getProperty("os.arch") = x86_64
System.getProperty("os.version") = 10.6.4
Honestly, don't hard-code absolute paths in a program, even for a single-platform app. Do the correct thing.
The following is my wrong solution, saved to remind myself not to repeat giving a misdirected advice ... shame on me.
Just create a symbolic link named Q: just at the root directory / to / itself.
$ cd /
$ ln -s / Q:
$ ln -s / S:
You might need to use sudo. Then, at the start of your program, just chdir to /.
If you don't want Q: and S: to show up in the Finder, perform
$ /Developer/Tools/SetFile -P -a V Q:
$ /Developer/Tools/SetFile -P -a V S:
which set the invisible-to-the-Finder bit of the files.
The only way you can replace java.io.File is to replace that class in rt.jar.
I don't recommend that, but the best way to do this is to grab a bsd-port of the OpenJDK code, make necessary changes, build it and redistribute the binary with your project. Write a shell script to use your own java binary and not the built-in one.
PS. Just change your config files! Practice your regex skills and save yourself a lot of time.
If you are not willing to change your config file per OS, what are they for in first place?
Every installation should have its own set of config files and use it accordingly.
But if you insist.. you just have to detect the OS version and if is not Windows, ignore the letter:
Something along the lines:
boolean isWindows = System.getProperty("os.name").toLowerCase()
.contains("windows");
String folder = "S:";
if (isWindows && folder.matches("\\w:")) {
folder = "/";
} else if (isWindows && folder.matches("\\w:.+")) {
folder = folder.substring(2);// ignoring the first two letters S:
}
You get the idea
Most likely you'd have to provide a different java.io.File implementation that can parse out the file paths correctly, maybe there's one someone already made.
The real solution is to put this kind of stuff (hard-coded file paths) in configuration files and not in the source code.
Just tested something out, and discovered something interesting: In Windows, if the current directory is on the same logical volume (i.e. root is the same drive letter), you can leave off the drive letter when using a path. So you could just trim off all those drive letters and colons and you should be fine as long as you aren't using paths to items on different disks.
Here's what I finally ended up doing:
I downloaded the source code for the java.io package, and tweaked the code for java.io.File to look for path names that start with a letter and a colon. If it finds one, it prepends "/Volumes/" to the path name, coughs a warning into System.err, then continues as normal.
I've added symlinks under /Volumes to the "drives" I need mapped, so I have:
/Volumes/S:
/Volumes/Q:
I put it into its own jar, and put that jar at the front of the classpath for this project only. This way, the hack affects only me, and only this project.
Net result: java.io.File sees a path like "S:/bling.properties", and then checks the OS. If the OS is OS X, it prepends "/Volumes/", and looks for a file in /Volumes/S:/bling.properties, which is fine, because it can just follow the symlink.
Yeah, it's ugly as hell. But it gets the job done for today.

How to open user system preferred editor for given file?

I'm trying to figure out how to open the system preferred editor for a given file.
Say, we have a file manager, written in Java. User goes to folder and sees the list of files. And, for example, there is a file Icon.jpg. User double clicks on the filename and file opens in system's preferred editor (i.e. Gimp). The main issue is - how to do that?
We can do Runtime.getRuntime().exec("something file"), but this way you should know which program is preferred in user environment. But how?
We also are able to do Desktop.getDesktop().edit(File file), but this way we cannot track process and aren't able to know then this child process is closed. Other issue - function doesn't work on linux (at least on Ubuntu 8.10). There is also Desktop.getDesktop().open(File file), but it forces to open file viewer, instead of system viewer for that file type.
I am searching for a solution all week, but didn't got any suitable and generic one. Do you know the other approaches to this question? For my project it would be enough if it would work on Windows+Linux+Mac.
Thank you for your answers and advices.
Edit on 2009-02-08 23:04
Other suggestion: can I force "application selection" window in Windows and in Linux, as in Mac with "open file"? For example, then you trying to open file, you are being asked to choose application from list of system preferred ones? (something like "Open with..." in Windows explorer). Do you know?
Seems that if you can't use java.awt.Desktop you have to distinguish between the OSes:
Windows:
RUNDLL32.EXE SHELL32.DLL,OpenAs_RunDLL <file.ext>
Linux:
edit <file.ext>
Mac:
open <file.ext>
HTH. Obviously, that is not very portable...
Check out the java.awt.Desktop object. In your case, you want to invoke edit()
If you want to ensure that a given platform supports this call, then you can do something like the following (I have not tested this code):
public boolean editFile(final File file) {
if (!Desktop.isDesktopSupported()) {
return false;
}
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.EDIT)) {
return false;
}
try {
desktop.edit(file);
} catch (IOException e) {
// Log an error
return false;
}
return true;
}
This isn't cross-platform, but on Mac OS X you can do
Runtime.getRuntime().exec("open filename");
The open(1) executable uses LaunchServices to pick the right program to execute, and then uses that to open the file named filename.
This will work in windows
Runtime.getRuntime().exec( "CMD /C START filename.ext " );
For JavaFX applications, we can use HostServices. This question covers how to use HostServices. This should work on Ubuntu (tested)/Windows (not tested) and Mac (not tested).
import java.io.File;
import java.io.IOException;
public class App extends Application {
}
File file = new File("/your/file/path");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
getHostServices() is a method of JavaFX Application class.

Categories

Resources