Getting hosts file location in Java - java

How can I get the location of the hosts file when using my application on different platforms?

think that you would have to roll your own here I'm afraid, as this is a pretty low level system function, I think that it's a little beyond what you could expect java to do for you.
This link points to some special options that you can set to alter the bind order, I don't think that they will tell you where the hosts file is, but you could could investigate in and around these options to see if you can find anything else to help you

You could use the "os.name" system property to determine the operating system. Then, retrieve the hosts file depending on where each operating system stores it. For example:
String osName = System.getProperty("os.name").toLowerCase();
File hostsFile;
if (osName.startsWith("mac os x")){
hostFile = new File("/etc/hosts");
} else if (osName.contains("windows")){
hostFile = //...
}

Take a look at the hosts file locations for each operating system and version on Wikipedia. Unfortunately you will have to implement your own logic similar to Michael's answer:
import java.awt.Desktop;
import java.io.File;
public class HostsFile
{
public static void main(String[] args) throws Exception
{
String osName = System.getProperty("os.name");
File hostsFile = null;
if (osName.contains("Windows"))
{
hostsFile = new File(System.getenv("WinDir")
+ "\\system32\\drivers\\etc\\hosts");
}
Desktop.getDesktop().open(hostsFile);
}
}

Related

How to crash my OS programatically?

Have written a Java code which sends mail when whole system RAM reaches > 95%.
I want to write a Java code to test this scenario. Have written few(recursive etc...), but those are crashing the JVM but not System.
Any help please ?
UN_ORTHODOX SOLUTION but it works anyway
NOTE! I Used WINDOWS 8.1 host machine
I found this DOC on myself too! in old days; about JVM and host system access issues. I used this code to get details about host system!
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
private static void printUsage() {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
for (Method method : operatingSystemMXBean.getClass().getDeclaredMethods()) {
method.setAccessible(true);
if (method.getName().startsWith("get")
&& Modifier.isPublic(method.getModifiers())) {
Object value;
try {
value = method.invoke(operatingSystemMXBean);
} catch (Exception e) {
value = e;
} // try
System.out.println(method.getName() + " = " + value);
} // if
} // for
}
NOTE !
that's not the real way To do but I did it by opening the Default browser (in most of cases I know most of the time its GOOGLE CHROME) , had 8GB ram those days so opening a few tabs with some random youtube and other links it helped me to reach up the memory usage unto 90% in no time! because it eats the RAM (No offence to CHROME people!) doing that I was able to achieve the test you are trying to get. :-)
TO Open a default browser just take a look on this thread its quite nice with different ways to do it!
well if you are using it for android well read about proguard rules for memory management and try using any external library which takes up too much memory like any dummy faceRecog library or simply just accessing some NDK features or so check this link for more

Reading subfolders within the registry (JAVA)

I'm busy creating a program that will read parts of the registry to find out what USB devices have been connected to a windows system etc... I've managed to create a piece of software what will display the values, however each person's registry will hold different information.
I've tried looking everywhere to find help/guidence with code to be able to scan a registry folder and display the subfolders within it. I know there is plenty of code for reading ordinary file locations however none will work with attempting to read the registry.
The folder location I am trying to read is:
"\"HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR\
I've managed to create a program which will read the values from the above location however I have to manualy specify each subfolder into the code.
I hope i've explained what i need, sorry if it's confusing
Thanks in advance
I've used jRegistryKey.dll jRegistryKey.jar
Here you go
ftp://ftp.heanet.ie/mirrors/sourceforge/j/project/jr/jregistrykey/manual/original/jreg_key.pdf
e.g. code:
import ca.beq.util.win32.registry.RegistryKey;
import ca.beq.util.win32.registry.RegistryValue;
import ca.beq.util.win32.registry.RootKey;
enumeration from example ---
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software");
if(r.hasSubkeys()) {
Iterator i = r.subkeys();
while(i.hasNext()) {
RegistryKey x = (RegistryKey)i.next();
System.out.println(x.toString());
} // while
} // if
RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, "Software\\app\\update\\Date");
if (r.hasValue("LastSuccessfulUpdate")) {
RegistryValue v = r.getValue("LastSuccessfulUpdate");
updateDate = v.getStringValue();
Date now = new Date(Long.parseLong(updateDate.trim() + "000"));
................
}

Set Java system properties with a configuration file

Is it possible to initialize Java system properties using some sort of configuration file?
(ie: can you set java.library.path using a file inside your jar)
EDIT: Clarification: I am asking specifically about initializing the system properties to a value in a file, not setting them later from inside the virtual machine. Yes, you can change system properties to whatever you want very easily after the machine starts up, but the Java system classes will not use the new values.
Practically speaking, this means System.setProperty and System.setProperties are useless for loading native libraries, as JNI will always use the original value of java.library.path to load libraries with. I'm trying to figure out if there's a cleaner alternative to just putting -Djava.library.path=whatever in start up scripts everywhere.
There is a way to set java.library.path programatically, see this.
The code is a hack to set the sys_path field on the ClassLoader,
System.setProperty( "java.library.path", "/path/to/libs" );
Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );
It would be pretty simple to do yourself:
public static void main(String[] args) {
Properties p = new Properties();
p.load(...); // Load the properties from a file in your jar
for (String name : p.stringPropertyNames()) {
String value = p.getProperty(name);
System.setProperty(name, value);
}
}
Use JAVA_TOOL_OPTIONS environment variable. _JAVA_OPTIONS may also work, but it's not documented at all. The JAVA_TOOL_OPTIONS is weakly documented, but here are some links:
http://www.oracle.com/technetwork/java/javase/envvars-138887.html#gbmsy
https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/envvars002.html
https://bugs.openjdk.java.net/browse/JDK-4971166
An example of use:
set JAVA_TOOL_OPTIONS=-Dmy.property=sth
When launching JVM you should see a message:
Picked up JAVA_TOOL_OPTIONS: ...
You cannot initialize them as far as I know, but you can definitely override their values to anything you want, using any source you wish.
I think the reason why System.setProperty(key,value) is useless for java.library.path in your program is your application is started, you need set it before your program is running.
Check your native library, if the library have any dependency that not included in the java.library.path, System.load will fail, as if System.setProperty(key, value) does not work as expected.
You can parse properties file with additional code (another instance of JVM), redirect its output to var and use this variable as parameter to your java invocation. For example:
public class SystemPropertyLoader {
public static void main(String[] args) throws Exception {
String file = args[0];//TODO check args
Properties properties = new Properties();
InputStream is = new FileInputStream(file);
properties.load(is);
is.close();
StringBuilder builder = new StringBuilder();
for (Entry e : properties.entrySet()){
builder.append("-D");
builder.append(e.getKey());
builder.append('=');
builder.append(e.getValue());
builder.append(' ');
}
System.out.println(builder.toString());
}
}
and
#!/bin/ksh
properties_variable=$(java SystemPropertyLoader input.properties)

How to obtain OS directory

I,m looking for some method that can let me obtain (in windows) the directory where windows is saved (for example in my PC it will return "C:\windows".
I need it because I have to call this method
public static void openFileWithNotepad(String pathFileTxt) throws InterruptedException, IOException
{
if(System.getProperty("os.name").toUpperCase().contains("Windows".toUpperCase()))
{
String program = "C:/WINDOWS/system32/notepad.exe";
Process p = Runtime.getRuntime().exec(program + " " + pathFileTxt);
}
...
}
I want to use some method to switch "C:/WINDOWS" with the OS installation folder, in order to use this program on different pcs.
P.S.: If someone know, I'd like also to know how to use this method on UNIX OSs :)
Thank you for understanding!
Desktop.getDesktop().open(new File(pathFileTxt));
Works for any file for which there is an associated program, on any OS that supports Java 1.6+. See Desktop.open(File) for details.
i believe this should work:
System.getenv("WINDIR")
also, notepad doesn't tend to exist on unix, so i'm not sure where you are going with that...
try
System.getenv("windir")
for windows.
I'm not sure about other OSs.
System.getenv("WINDIR") may work for you.

Portable Device Path on Windows

I've actually got an Windows/Java Question. I've got a plugged-in device which I want to access via Java. Normally you can access an e.g. USB-Stick via the Drive letter... but this tablet is displayed by Windows as a "Portable Device"... which means, that the Path is something like "Computer\Archos 5S" and there is no Drive letter.
I want to access a file on this device via Java, but I am not able to figure out the correct path to it. There is a similar question out there, but without a productive answer. Or is there another way to access this device via Java?
Actually I've not solved this problem... I am still not able to access such a device via java.
At the moment I am trying to access a windows ShellFolder in Java.
A Shellfolder like: "Shell:::{35786D3C-B075-49b9-88DD-029876E11C01}"
Is this possible with Java?
Recently I uncovered the sun.awt class "ShellFolder"... is this the wanted feature?
thanks for your help
Ripei
The solution to above problem using JMTP library on https://code.google.com/p/jmtp/
Here is my code
package jmtp;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.Guid;
import java.io.*;
import java.math.BigInteger;
import jmtp.PortableDevice;
import jmtp.*;
public class Jmtp {
public static void main(String[] args) {
PortableDeviceManager manager = new PortableDeviceManager();
PortableDevice device = manager.getDevices()[0];
// Connect to my mp3-player
device.open();
System.out.println(device.getModel());
System.out.println("---------------");
// Iterate over deviceObjects
for (PortableDeviceObject object : device.getRootObjects()) {
// If the object is a storage object
if (object instanceof PortableDeviceStorageObject) {
PortableDeviceStorageObject storage = (PortableDeviceStorageObject) object;
for (PortableDeviceObject o2 : storage.getChildObjects()) {
//
// BigInteger bigInteger1 = new BigInteger("123456789");
// File file = new File("c:/JavaAppletSigningGuide.pdf");
// try {
// storage.addAudioObject(file, "jj", "jj", bigInteger1);
// } catch (Exception e) {
// //System.out.println("Exception e = " + e);
// }
//
System.out.println(o2.getOriginalFileName());
}
}
}
manager.getDevices()[0].close();
}
}
Do not forget add jmtp.dll files (that comes up with jmtp download) as a native library. For more info, see my answer on Including Native Library in Netbeans.
Like *nix systems, all devices (including drives) have paths that are part of a common root, this is normally hidden from users because they use the drive letters which are aliases to these fundamental paths, but you can also use full device paths by prefixing the path with "\\.\"
For instance, on my machine D: translates as "\Device\HarddiskVolume1" and can be accessed by passing "\\.\HarddiskVolume1" to CreateFile.
So the path to your device is probably "\\.\Archos 5s".
you can always download and install the Windows mobile developer Powertoys (http://www.microsoft.com/download/en/details.aspx?id=10601) and copy from and to the device using the command line utility cecopy, which you can run from any programming language. There are other options there too, but it's most targeted at .Net

Categories