Java string (source code) to show in browser - java

I am programming a Java application that inspects the source code of a webpage an shows that webpage to me in my default browser when a condition in the source code is satisfied.
I get my source code the following way:
String source = getUrlSource(myURL);
To show a specific webpage I know I can use:
java.awt.Desktop.getDesktop().browse(myURI);
But this is not enough for my application because of variable content, How can I get java to show me the webpage that is encoded in the string source? I need the equivalent of something that would look like
java.awt.Desktop.getDesktop().browse(sourceCodeString).
Update: If the condition is not satisfied, it will reload the same page. So the complete program executes on 1 url. Java is probably not the right language for that purpose, maybe someone has a better language to do this behaviour>
Thanks for your help,

You can save the string in a file and open the file.
public class Test {
public static void main(String[] args) throws IOException {
String html = "<html><body>Hello Browser</body></html>";
File file = new File("test.html");
FileWriter writer = new FileWriter(file);
writer.write(html);
writer.close();
Desktop.getDesktop().browse(file.toURI());
}
}

Related

How to write to file synchronously using java?

I just started learning Java and I was interested in the File libraries. So I kept a notepad file open called filename.txt. Now I want to write to file using Java, but I want to get the result in real time.
I.e when the java code executes the changes should be visible in the text file without closing and reopening the file.
Here my code:
import java.io.*;
class Locker
{
File check = new File("filename.txt");
File rename = new File("filename.txt");
public void checker()
{
try{
FileWriter chk = new FileWriter("filename.txt");
if(check.exists())
{
System.out.println("File Exists");
chk.write("I have written Something in the file, hooray");
chk.close();
}
}
catch(Exception e)
{
}
}
};
class start
{
public static void main(String[] args)
{
Locker l = new Locker();
l.checker();
}
}
Is it possible and if so can someone tell me how?
Simple answer: this doesn't depend on the Java side.
When your FileWriter is done writing, and gets closed, the content of that file in your file system has been updated. If that didn't happen for some reason, you some form of IOException should be thrown while running that code.
The question whether your editor that you use to look at the file realizes that the file has changed ... completely depends on your editor.
Some editors will ignore the changes, other editors will tell you "the file changed, do you want to reload it, or ignore the changes".
Meaning: the code you are showing does "synchronously" write that file, there is nothing to do on the "java side of things".
In other words: try using different editors, probably one intended for source code editing, like atom, slickedit, visual studio, ...

(Processing) Converting type file into type string?

I'm trying to get my application to open an audio file via a button (which works) and display the data of the file in the console (which also works)
The application is unable to play the file because the function needs a type String and the audio file I'm using is of type File. How do you convert a File into a String in Processing?
void setup() {
selectFile();
size(300, 300);
}
void selectFile() {
selectInput("Select a file to process:", "fileSelected");
}
void songTag(File selection) {
File file = new File(selection.getPath());
song = minim.loadFile(filepath);
song.play();
}
}
}
Check out the Java API to understand Java classes and functions.
The File class has several useful functions. You probably want the getAbsolutePath() function.
I'm not sure which line of code is showing the compiler error, but you might try something like this:
Mp3File mp3file = new Mp3File(selection.getAbsolutePath());
song = minim.loadFile(selection.getAsbolutePath());
Also note that the code you posted has other errors: the filepath function is never defined, for example. In the future, please try to post a MCVE that actually shows exactly what you're trying to do.

Java - How can I more effectively "scan" a portion of my file system with this program?

I am working on part of a proof of concept program in Java for an antivirus idea I had. Right now I'm still just kicking the idea around and the details aren't important, but I want the program I'm writing to get the file paths of every file within a certain range of each other(say 5 levels apart) in the directory and write them to a text file.
What I have right now(I will include my code below) can do this to a limited extent by checking if there are files in a given folder in the directory and writing their file paths to a text file, and then going down another level and doing it again. I have it set up to do 2 levels in the directory currently and it sort of works. But it only works if there is only one item in the given level of the directory. If there is one text file it will write that filepath to another text file and then terminate. But if there's a text file and folder, it ignores the text file and goes down to the next level of directory and records the file path of whatever text file it finds there. If there are two or more folders it will always choose one in particular over the other or others.
I realize now that it's doing that because I used the wrong conditional. I used if else and should have done something else, but I'm not sure which one I should have used. However I have to do it, I want to fix it so that it branches out with each level. For example, I start the program and give it starting directory C:/Users/"Name"/Desktop/test/. Test has 2 folders and a text file in it. Working the way I want it to, it would then record the file path of the .txt, go down a level into both folders, record any .txts or other files it found there, and then go down another level into each folder it found in those two folders, record what it found there, and so on until it finished the pre-determined number of levels to go through.
EDIT: To clarify confusion over what the problem is, I'll sum it up. I want the program to write the file paths of any files it finds in each level of the directory it goes through in another text file. It will do this, but only if there is one file in a given level of directory. If there is just one .txt for example, it will write the file path of that .txt to the other text file. But if there are multiple files in that level of directory(for example, two .txts) it will only write the file path of one of them and ignore the other. If there's a .txt and a folder, it ignores the .txt and enters the folder to go to the next level of directory. I want it to record all files in a given location and then branch into all the folders in that same location.
EDIT 2: I got the part of my code that gets the file path from this question( Read all files in a folder ) and the section that writes to my other text file from this one( How do I create a file and write to it in Java? )
EDIT 3: How can I edit my code to have recursion, as #horatius pointed out that I need?
EDIT 4: How can I edit my code so that it doesn't need a hard coded starting file path to work, and can instead detect the location of the executable .jar and use that as its starting directory?
Here is my code:
public class ScanFolder {
private static final int LEVELS = 5;
private static final String START_DIR = "C:/Users/Joe/Desktop/Test-Level1/";
private static final String REPORT_FILE = "C:/Users/Joe/Desktop/reports.txt";
public static void main(String[] args) throws IOException {
try (PrintWriter writer = new PrintWriter(REPORT_FILE, "UTF-8");
Stream<Path> pathStream = Files.walk(Paths.get(START_DIR), LEVELS)) {
pathStream.filter(Files::isRegularFile).forEach(writer::println);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
Thanks in advance
If you are using Files.walk(...) it does all the recursion for you.
Opening and writing to the PrintWriter will truncate your output file each time it is opened/written to, leaving just the last filename written.
I think something like the below is what you are after. As you progress, rather than writing to a file, you may want to put the found Path objects into an ArrayList<Path> or similar for easier later processing, but not clear from your question what requirements you have here.
public class Walk
{
public static void main(String[] args) throws IOException {
try (PrintWriter writer = new PrintWriter("C:/Users/Joe/Desktop/reports.txt", "UTF-8")) {
Files.walk(Paths.get("C:/Users/Joe/Desktop/test")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
writer.println(filePath);
}
});
}
}
}
Here is an improved example that you can use to limit depth. It also deals with properly closing the Stream returned by Files.walk(...) that the previous example did not, and is a little more streams/lambda idiomatic:
public class Walk
{
// Can use Integer.MAX_VALUE for all
private static final int LEVELS = 2;
private static final String START_DIR = "C:/Users/Joe/Desktop/test";
private static final String REPORT_FILE = "C:/Users/Joe/Desktop/reports.txt";
public static void main(String[] args) {
try (PrintWriter writer = new PrintWriter(REPORT_FILE, "UTF-8");
Stream<Path> pathStream = Files.walk(Paths.get(START_DIR), LEVELS)) {
pathStream.filter(Files::isRegularFile).forEach(writer::println);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}

Using selenium webdriver to upload a file

I'm trying to build some automated test for a mailbox application and I'm trying to attach a file. I've read all the documentation from previous post and was able to come up with this:
public void I_attach_a_file_that_exceeds_the_limit() throws Throwable {
WebElement attachFile = driver.findElement(By.id("attachment"));
File f = new File("C:\\coop-provider-swm-specs\\src\\test\\resources\\attachments\\20481kb.txt");
attachFile.sendKeys(f.getCanonicalPath());
}
The problem with this is that the file that it attaches is not the real file. The file that is attached is blank (not sure how that works). The file that I need to attach is a big file and I need to do this in order the authenticate that the user does not exceed the limit for attachments that is allowed.
Change:
attachFile.sendKeys(f.getCanonicalPath());
To:
attachFile.sendKeys(f.getCanonicalPath()).submit();

Error Parsing File JSP or JAVA in Netbeans 7.3.1

I migrated my project from Net beans 6.9.1 to Net Beans 7.3.1 and faced this annoying error a red exclamation icon on a random file jsp or java .
I opened them and did not find any error.
I tried some suggestions after searching Google to disable html and jsp validation with no luck , another suggestion was to delete the cache files under user directory folder cache at C:\Users\home\.netbeans\6.9\var\cache and also without luck !!!
resolve bug incomplete
sample of java file error
You can try to do the following ... it worked for me
rename the file of jsp or java to make the error go away for example
test.java renamed to test_.java and then renamed back to test.java
also same for jsp or xml
references
translate it to english
By working with netbenas on some projects in some of these projects
netbeans files mark some files with the symbol of admiration and the
message "Error parsing file". This occurs because of a problem
netbenas cache. The solution to this is to close the netbenas, clean
(delete cache files and start the netbenas will return. Here are the
different routes of some operating systems cache. WINDOWS: C: \ Users
\ AppData \ Local \ NetBeans \ Cache \ 7.2 \ MAC OS X: / Users //
Library/Caches/NetBeans/7.2 / UNIX: / home // .cache/netbeans/7.2
good luck
i fixed "Error Parsing File" in my Java file (IDE: Netbeans) by just deleting the space before the bottom most "}" and press enter. Basically, just do some modification in the file and save it again.
In my case I had a class similar to the following and Netbeans (8.2) showed no error inside the file, but in the file icon it showed a error of parsing the file:
public class FileUploadUtil {
private static interface WriteToFile {
public void run(File file) throws IOException;
}
private static interface UseFile {
public void run(File file) throws IOException;
}
private static void createAndUseTempFile(InputStream is, UseFile use) throws IOException {
createAndUseTempFile((file) -> {
try (FileOutputStream fos = new FileOutputStream(file)) {
byte[] bytes = new byte[1024];
int read;
while ((read = is.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
fos.flush();
}
}, use, "tmp");
}
private static void createAndUseTempFile(Image image, UseFile use, String extension) throws IOException {
createAndUseTempFile((file) -> image.writeToFile(file), use);
}
private static void createAndUseTempFile(WriteToFile write, UseFile use, String extension) throws IOException {
File file = null;
try {
String key = System.currentTimeMillis() + "-" + SecurityUtil.generateUUID();
String suffix = (extension != null) ? ("." + extension) : null;
file = File.createTempFile(key, suffix);
write.run(file);
use.run(file);
} finally {
if (file != null) {
file.delete();
}
}
}
}
The method:
private static void createAndUseTempFile(Image image, UseFile use, String extension) throws IOException {
createAndUseTempFile((file) -> image.writeToFile(file), use);
}
should be:
private static void createAndUseTempFile(Image image, UseFile use, String extension) throws IOException {
createAndUseTempFile((file) -> image.writeToFile(file), use, extension);
}
but Netbeans showed no errors inside the file, so I tried to reload the project, rename the file and so on.
Then I tried to compile with gradle and received the error:
FileUploadUtil.java:95: error: incompatible types: InputStream is not a functional interface
Then I realized that it was trying to call createAndUseTempFile(InputStream is, UseFile use) instead of createAndUseTempFile(WriteToFile write, UseFile use, String extension), but because the InputStream is not a functional interface and doesn't extends/implements an interface that has a method that receives a File, it couldn't call that method (and shouldn't!).
I think it's a Netbeans bug in this case, because it should show the error in that line.
Sometimes I had these issues with embedded JavaScripts in the JSP files, especially if the JavaScript parts contained JSTL EL expressions. In these cases the NetBeans project tree view showed a red exclamation mark ("Error parsing file") for the JSP file but when opening the file it didn't show a single error for a line.
Idea 1: Add HTML comments to the JavaScript part in order to make the JSP/HTML syntax highlighter engine ignore these parts:
<b>Very primitive example</b>
<script type="text/javascript">// <!--
var foo = ${myBean.bar}; // -->
</script>
Idea 2: Put as much JavaScript code as possible into external JS files. In general it's a good idea to avoid JavaScript code in JSP/HTML files as this allows you to use additional anti XSS measures like X-XSS-Protection.
May occur if having unnecessary lambda return statement in Netbeans 8.2
I'm not sure if this is helpful but I was using netBeans IDE 8.2 and one of my Dialogs exampleDialog.java showed a redmark on it and there were no errors in the file.
I was using Dimension wndSize;
wndSize = theKit.getScreenSize();
and in setting the window size I was using wndSize.getWidth(); and wndSize.getHeight(); these were wrong I changed them to wndSize.width; and wndSize.height;
and the red mark disappeared.
regards Michael.
No need to worry ! This is because after you make any changes in servets or jsp you need to save your file.
So first save your file then everything goes well.
This worked for me!

Categories

Resources