I'm trying to make a java program which blocks the facebook page in web browsers. I'm trying to overwrite somehow the hosts file, but the file is disabled to overwriting. I tried to copy him to my desktop, then append a line which blocks the page, and then copy to the etc folder and click to copy (or overwrite) the file. But i can't do it in java, all what i did was create another file in the same folder and append lines to it. But then i can't copy the new file to old, i dont know how to do it, here's my code, i'm waiting for a solutions :)
public class Sandbox {
private final static File zdroj = new File("C:\\Windows\\System32\\drivers\\etc\\hosts");
private final static File ciel = new File("C:\\Windows\\System32\\drivers\\etc\\hostsTemp");
public static void main(String[] args) {
try {
Files.copy(zdroj.toPath(), ciel.toPath());
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(ciel, true)));
writer.append("\n\n127.0.0.1 facebook.com www.facebook.com http://www.facebook.com/ http://facebook.com");
writer.close();
Files.delete(zdroj.toPath());
Files.copy(ciel.toPath(), zdroj.toPath());
} catch (IOException ex) {
Logger.getLogger(Sandbox.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
You will need to run your application with elevated permissions. Try starting it with some administrator user.
Related
I am using Lobo Browser in NetBeans 11.2 and I cant run the program because NetBeans cannot read which file has the Main class which is in the main browser file (main class of main browser code below)
I would like to get this working because I need some code that I want to steal but I would like to see how the browser runs first.
public static void main(final String[] args) {
// Detect if we are running on mac
if (isMac()) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("dock.name", "LoboBrowser");
}
// Checking for stack allows us to call AccessController.doPrivileged()
// which in turn allows us to reduce the permissions on Uno codesource
final int stackDepth = Thread.currentThread().getStackTrace().length;
if (stackDepth > 11) {
System.err.println("Stack depth (" + stackDepth + ") is too deep! Quitting as a safety precaution");
Thread.dumpStack();
System.exit(1);
} else {
privilegedLaunch(args);
}
}
private static void launch(final String[] args) {
try {
final SSLSocketFactory socketFactory = TrustManager.makeSSLSocketFactory(ReuseManager.class.getResourceAsStream("/trustStore.certs"));
ReuseManager.getInstance().launch(args, socketFactory);
} catch (final Exception err) {
final StringWriter swriter = new StringWriter();
final PrintWriter writer = new PrintWriter(swriter);
err.printStackTrace(writer);
writer.flush();
JOptionPane.showMessageDialog(new JFrame(),
"An unexpected error occurred during application startup:\r\n" + swriter.toString(),
"ERROR", JOptionPane.ERROR_MESSAGE);
System.err.println(swriter.toString());
System.exit(1);
}
}
I believe you have to put the main method with in a class as described here http://tutorials.jenkov.com/java/main-method.html. I know in net beans you can tell it what class to try to run by I think right clicking the run then selecting what file to run and if its set up correctly it will run the file.
using java 8, tomcat 8
Hi, i am loading a file using properties, but i have a check before loading which returns the same properties object if its already been loaded (not null). which is a normal case scenario but i want to know if there is any way that if any change occur in target file, and some trigger should be called and refreshes all the properties objects. here is my code.
public static String loadConnectionFile(String keyname) {
String message = "";
getMessageFromConnectionFile();
if (propertiesForConnection.containsKey(keyname))
message = propertiesForConnection.getProperty(keyname);
return message;
}
public static synchronized void getMessageFromConnectionFile() {
if (propertiesForConnection == null) {
FileInputStream fileInput = null;
try {
File file = new File(Constants.GET_CONNECTION_FILE_PATH);
fileInput = new FileInputStream(file);
Reader reader = new InputStreamReader(fileInput, "UTF-8");
propertiesForConnection = new Properties();
propertiesForConnection.load(reader);
} catch (Exception e) {
Utilities.printErrorLog(Utilities.convertStackTraceToString(e), logger);
} finally {
try {
fileInput.close();
} catch (Exception e) {
Utilities.printErrorLog(Utilities.convertStackTraceToString(e), logger);
}
}
}
}
the loadConnectionFile method executes first and calls getMessageFromConnectionFile which has check implemented for "null", now if we remove that check it will definitely load updated file every time but it will slower the performance. i want an alternate way.
hope i explained my question.
thanks in advance.
Java has a file watcher service. It is an API. You can "listen" for changes in files and directories. So you can listen for changes to your properties file, or the directory in which your properties file is located. The Java Tutorials on Oracle's OTN Web site has a section on the watcher service.
Good Luck,
Avi.
I have the following script, of which you can see below. The function of this Java script is to copy a Mac app, of which is placed in the same folder as the java program. It first finds the path of the folder, which the app and java program is in. It then copies all the content to the documents folder on the Mac device. When that is done it is then supposed to run that app of which it has copied to the documents folder.
The only issue is that it isn't able to do so. The reason being that whenever it copies the app, the JavaAppLauncher which is found within the content of the mac app has changed from a unix executable to a regular TextEdit document and thus can't actually launch the app. However if I were to copy the app manually by copying it myself and not using the java program, there is no issue. I am not sure whether this issue is caused by my code, or whether it is just a general thing?
Important note, the .app does work when I just run the regular non copied version, but as soon as it is the copied version, which as been copied through Java it doesn't work because the change of the Unix executable.
public class LaunchProg {
static String usernameMac2 = System.getProperty("user.name");
static File propFile = new File (".");
static String pathString = propFile.getAbsolutePath();
static int pathhLeng = pathString.length();
static int pathReaLeng = pathhLeng -1;
static String filNamMac = "AppNam.app";
static String pFPathRelMac = pathString.substring(0,pathReaLeng);
private static final File fSourceMac = new File(pFPathRelMac);
private static final File AppFold = new File ("/Users/" + usernameMac2 + "/Documents");
static File fileCret = new File("fCret.txt");
public static void main(String[] args) throws IOException {
System.out.println(pFPathRelMac);
launchMac();
}
static void launchMac() throws IOException {
if (!fileCret.exists()){
try {
FileUtils.copyDirectory(fSourceMac, AppFold);
PrintWriter pFW = new PrintWriter(fileCret);
pFW.println("Created File For Check");
pFW.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
String command = "open /Users/" + usernameMac2 + "/Documents/AppNam.app";
Process staAp2 = Runtime.getRuntime().exec(command);
}
}
}
}
I'm trying to print out the usernames of a certain program into a file but PrintWriter is not printing anything on my file. I've tried everything mentioned on stackOverFlow none of them worked.
Users Class
private File usersListFile;
private PrintWriter usersListPrintWriter;
private Scanner usersListScanner;
Constructor:
Users(){
try {
this.usersListFile = new File("D:\\Dairy\\usersList.txt");
if(usersListFile.exists()){
this.usersListPrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("D:\\Dairy\\usersList.txt", true)));
this.usersListScanner = new Scanner("D:\\Dairy\\usersList.txt");
}
else
System.err.println("File does not exist !");
}
catch(Exception e){
System.err.println("Error: Users Class!");
}
}
Method:
public void addToUsersList(String username){
usersListPrintWriter.print(username);
}
Main Method:
public static void main(String[] args) {
Users usersObject = new Users();
usersObject.addToUsersList("USERNAME");
}
usersListPrintWriter is buffered, so you need to flush the data (as Alexandro mentioned too).
You also likely will need to change the print into a println so newly added users are output on separate lines.
Your Scanner will not work, since you're scanning the given string, not the file content. Use new Scanner(this.usersListFile) instead.
You should also re-use your File object on the previous line: new FileWriter(this.usersListFile, true)
And I would say that having a Writer and a Scanner open on the same file at the same time is a bad idea, if it even works. You should probably just load all the users into memory and close the scanner before opening the writer, unless you have
public void addToUsersList(String username){
usersListPrintWriter.print(username);
usersListPrintWriter.flush();
}
Then, when you don't need anymore your printwriter, call close().
Ok, simply put I am making a quiz game in a java applet, and I want to serialize an object which stores the high scores. When I do this it works perfectly in eclipse but not in a browser.
Here is the code of my applet where it reads the file:
and yes I have all of the appropriate imports
package histApplet;
public class QuizApplet extends Applet
{
private static final String TRACKERLOC = "histApplet/track.ser";
private StatsTracker tracker;
private int difflevel = 1;
//other instance variables
public void init()
{
//other code
if(new File(TRACKERLOC).exists())
{
tracker = null;
FileInputStream fis = null;
ObjectInputStream in = null;
try
{
fis = new FileInputStream(TRACKERLOC);
in = new ObjectInputStream(fis);
tracker = (StatsTracker)in.readObject();
in.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
}
else
{
tracker = new StatsTracker(difflevel);
}
//other code
}
And here is my html code
<html>
<head><title>QuizApplet</title></head>
<body>
<center><applet code="histApplet/QuizApplet.class" height=550 width=700>
</applet></center>
</body>
</html>
If I comment out this code it works in a browser but otherwise doesn't. I'm not sure why this doesn't work, and any help would be greatly appreciated.
See my answer on how to write into a text file in Java.
Java Applets execute in a sandbox within the browser, so have limited access to resources in the client machine running the applet (into the browser). File system can't be accessed by an Applet, as explained in several sites SecuringJava, Oracle.
You need to sign your Applet (trusted code) in order to get access to the file system, Oracle.
As written by David, applets can't access the local file system.
They can send data to the host they came from (and receive answers from there), so you could store the highscores on the server, if you have some server-side program which accepts these highscores there.
An alternative would be using a JNLP-deployed applet, then your applet could access an applet-specific local storage with a PersistenceService.