So im trying to make a program that you input a flash game URL and it downloads the .swf file. Shown here:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Main.java
*
*
*/
public class Main {
/**
* Reads a web page into a StringBuilder object
* and prints it out to console along with the
* size of the page.
*/
public void getWebSite() {
try {
URL url = new URL("http://www.vivalagames.com");
URLConnection urlc = url.openConnection();
BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
StringBuilder builder = new StringBuilder();
int byteRead;
while ((byteRead = buffer.read()) != -1)
builder.append((char) byteRead);
buffer.close();
Logger.log(builder.toString());
System.out.println("The size of the web page is " + builder.length() + " bytes.");
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Starts the program
*
* #param args the command line arguments
*/
public static void main(String[] args) {
new Main().getWebSite();
}
}
I have got to the part where it downloads the websites html and puts it into a file called output.txt. Now what im trying to do is make it search that text file till it finds the words ".swf", the searcher code is:
import java.io.*;
import java.util.Scanner;
import java.util.regex.MatchResult;
public class Sercher {
public static void main() throws FileNotFoundException {
Scanner s = new Scanner(new File("output.txt"));
while (null != s.findWithinHorizon("(?i)\\b.swf\\b", 0)) {
MatchResult mr = s.match();
System.out.printf("Word found: %s at index %d to %d.%n", mr.group(),
mr.start(), mr.end());
}
}
}
Now how do I make the main.java code run the function from the Searcher.java?
This should do it:
public static void main(String[] args) {
new Main().getWebSite();
Searcher.main();
}
Make an instance of the Searcher class in the Main class.
public static void main(String[] args) {
new Main().getWebSite();
Searcher search = new Searcher();
}
or simply, use Searcher.main();.
First of all, storing the downloaded HTML in a file to re-read this file right after is not a really good idea. You could do everything in memory.
Think in terms of objects and methods. You basically have two objects here: a Downloader and a Searcher. And you don't want two main methods to your program: only a single one. This main method should look like this:
// create the object which downloads the HTML
Downloader downloader = new Downloader();
// Ask it to download, and store the result into a String variable
String downloadedHtml = downloader.download();
// create the object which can search into a String for .swf references
Searcher searcher = new Searcher();
// pass it the String to search into
searcher.searchSwfIn(downloadedHtml);
You need to put your classes to packages and import Searcher package to your main class.
Example:
package foo.bar.package;
import for.bar.package2.Searcher;
/*
Other import declarations
*/
public class Main {
/*
Your code
*/
public static void main(String[] args) {
new Main().getWebSite();
new Searcher().search();
}
}
package for.bar.package2;
/*
Import declarations
*/
public class Searcher {
public void search() throws FileNotFoundException {
Scanner s = new Scanner(new File("output.txt"));
while (null != s.findWithinHorizon("(?i)\\bjava\\b", 0)) {
MatchResult mr = s.match();
System.out.printf("Word found: %s at index %d to %d.%n", mr.group(),
mr.start(), mr.end());
}
}
}
Related
I'm trying to make my own pretty print for java files, similar to JDoodle. How can I compile a java class, given either it's location as a string, or its content as a string, as well as do it given a text file for std inputs, all the while recording the output as a seperate string. Sorry if this seems troublesome. Any help is appreciated!
EDIT: I do know about the java.tools.ToolProvider and Tool, but even if it is the solution, I don't know what to do with it, as the documentation is too confusing for me, or too sparse.
OK, I got an answer. I used Eclipse's compiler(cause I dont have JDK in my school laptop) to compile and used processbuilder to run the produced .class file, redirected the output using redirectOutput to a file which I read to get the output. Thanks- Here is the code.
/*PRETTYPRINT*/
/*
* Code to HTML
* Uses highlightjs in order to create a html form for your code, you can also give inputs and outputs
* */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class PrettyPrint {
public static void main(String[] args) throws FileNotFoundException{
String javaFile = readFile(args[0]);
String commandLine = readFile(args[1]);
String output = readFile(args[2]);
String html = "<!DOCTYPE html>\n"
+"<html>\n"
+"<head>"
+"<link rel=\"stylesheet\" href=\"highlightjs/styles/a11y-dark.css\" media= \"all\">\r\n"
+"<script src=\"highlightjs/highlight.pack.js\"></script>\r\n"
+"<script>hljs.initHighlightingOnLoad();</script>"
+"<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js\" integrity=\"sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/\" crossorigin=\"anonymous\"></script>\r\n"
+"<script src=\"https://cdn.jsdelivr.net/npm/html2canvas#1.0.0-rc.5/dist/html2canvas.min.js\"></script>"
+"<meta charset=\"utf-8\">"
+"<style>code{overflow-x: visible;}body{background-color:#888888;color:#444444;}h1{text-align:center;color:#444444;}</style>"
+"</head>"
+"<body style=\"font-family: 'Consolas';\">\n"
+"<h1 style=\"text-align: center\">Java Code</h1>"
+"<pre><code class=\"java\" style=\"overflow-x:visible\">"
+toHTML(javaFile)
+"</code></pre>"
+"<br>\n"
+"<h1>Inputs</h1>"
+"<pre><code class = \"nohighlight hljs\" style=\"overflow-x:visible\">"
+toHTML(commandLine)
+"</code></pre>"
+"<br>\n"
+"<h1>Output</h1>"
+"<pre><code class = \"nohighlight hljs\" style=\"overflow-x:visible\">"
+toHTML(output)
+"</code></pre>"
+"</body>\n"
+"<script>"
+"console.log(document.body.innerHTML);"
//+String.format("function print(){const filename='%s';html2canvas(document.body).then(canvas=>{let pdf = new jsPDF('p','mm', 'a4');pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 1000, 1000);pdf.save(filename);});}print();",args[3].substring(args[3].lastIndexOf('/')+1, args[3].length()-4)+"pdf")
+ "</script>"
+"</html>\n";
//System.out.println(html);
try {
File file = new File("output.html");
PrintWriter fileWriter = new PrintWriter(file);
fileWriter.print(html);
fileWriter.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public static String toHTML(String str) {
String html = str;
html = html.replace("&","&");
html = html.replace("\"", """);
html = html.replace("\'", "'");
html = html.replace("<", "<");
html = html.replace(">", ">");
//html = html.replace("\n", "<br>");
html = html.replace("\t", " ");
html+= "<br>";
return html;
}
public static String readFile(String filePath)
{
String content = "";
try
{
content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
}
catch (IOException e)
{
e.printStackTrace();
}
return content;
}
}
/**PROCESSBUILDEREXAMPLE**/
import java.io.*;
import org.eclipse.jdt.core.compiler.CompilationProgress;
import org.eclipse.jdt.core.compiler.batch.BatchCompiler;
public class ProcessBuilderExample {
private static String JAVA_FILE_LOCATION;
public static void main(String args[]) throws IOException{
JAVA_FILE_LOCATION = args[0];
CompilationProgress progress = null;
BatchCompiler.compile(String.format("-classpath rt.jar %s",args[0]), new PrintWriter(System.out), new PrintWriter(System.err), progress);
Process process = new ProcessBuilder("java", "-cp",
JAVA_FILE_LOCATION.substring(0,JAVA_FILE_LOCATION.lastIndexOf("\\")),
JAVA_FILE_LOCATION.substring(JAVA_FILE_LOCATION.lastIndexOf("\\")+1,JAVA_FILE_LOCATION.length()-5))
.redirectInput(new File(args[1]))
.redirectOutput(new File(args[2])).start();
try {
process.waitFor();
PrettyPrint.main(args);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Keep these 2 in the same folder and run processbuilderexample with 3 arguments. The code's loc, the input file's loc, and the output file to write to.
I have two text files namely - item.txt (file 1) and temp.txt (file 2). My goal is to search for a name in the file 1 and if found then replace it with a different name and write the updated line to file 2. Also, I have a method that checks for the lines for the string I searched in file 1. The lines that do not contain that string will be added to file 2.
So, here is where I'm stuck. Everything works fine except the part where I want to delete file 1 and rename file 2 by file 1 (i.e item.txt). Can someone please help me with any correction? I am still a beginner in Java, so my code might not be the best looking code as one might expect but this is what I tried so far. Thanks
The problem is when i compile the code the updated data is written to file2 and file1 which was supposed to get deleted doesn't delete. So, what could be the problem?
package project4;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class kitkat {
PrintWriter out,in;
Scanner in;
Scanner temp;
File file1 = new File("item.txt");
File file2 = new File("temp.txt");
public void write() throws FileNotFoundException {
out = new PrintWriter(file1);
out.println("User1"+ "\t"+"639755"+"\t"+"400");
out.println("User2"+ "\t"+"639725"+"\t"+"800");
out.close();
}
public void nfile() throws IOException {
n = new PrintWriter(new FileWriter(file2,true));
}
Scanner input = new Scanner(System.in);
String replacement = "User3";
String search;
String total;
public void search() {
System.out.println("Enter your search name");
search = input.nextLine();
total = search;
}
public void lolipop() throws IOException {
in = new Scanner(file1);
search();
while(in.hasNext()) {
String a,b,c;
a = in.next();
b = in.next();
c = in.next();
if(a.contains(search)) {
System.out.println("Your match is found"+search);
a = replacement;
System.out.println(a+b+c);
n.file();
n.println(a+"\t"+b+"\t"+c);
n.close();
}
}
}
public void jellybeans() throws IOException {
temp = new Scanner(file1);
while(temp.hasNext()) {
String p,q,r;
p = temp.next();
q = temp.next();
r = temp.next();
if(!(p.contains(total))) {
System.out.println(p+q+r);
n.file();
n.println(p+"\t"+q+"\t"+r);
n.close();
renamefile();
}
}
}
public void renamefile() {
file1.delete();
file2.renameTo(file1);
}
}
package project4;
import java.io.FileNotFoundException;
import java.io.IOException;
public class tuna {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
kitkat kt = new kitkat();
kt.lolipop();
kt.jellybeans();
}
}
Change this:
public void renamefile() {
String file1Path = file1.getAbsolutePath();
file1.delete();
file2.renameTo(new File(file1Path));
}
According to the Javadoc of File.renameTo(…) the behavior of this method is platform dependent. If the rename does not succeed it simply returns false without throwing an exception. So I guess this would be the case here.
You can try the newer (since Java 7) Files.move(…). This method is platform independent and has propper error handling, throwing exceptions with a problem description.
Trying to run a java program through Powershell. I go to my directory and use javac Part1.java and then to run the class I use java Part1 but it gives me this error Error: Could not find or load main class Part1 Here is the code in Part1.java which takes a basic .in text file and does some cool stuff with the each line in the .in document:
package comp2402a1;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.*;
public class Part1 {
/**
* Your code goes here - see Part0 for an example
* #param r the reader to read from
* #param w the writer to write to
* #throws IOException
*/
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
// Your code goes here - see Part0 for an example
SortedSet<String> s = new TreeSet<String>();
for (String line = r.readLine(); line != null; line = r.readLine()) {
s.add(line);
}
for (String text : s) {
w.println(text);
}
}
/**
* The driver. Open a BufferedReader and a PrintWriter, either from System.in
* and System.out or from filenames specified on the command line, then call doIt.
* #param args
*/
public static void main(String[] args) {
try {
BufferedReader r;
PrintWriter w;
if (args.length == 0) {
r = new BufferedReader(new InputStreamReader(System.in));
w = new PrintWriter(System.out);
} else if (args.length == 1) {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(System.out);
} else {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(new FileWriter(args[1]));
}
long start = System.nanoTime();
doIt(r, w);
w.flush();
long stop = System.nanoTime();
System.out.println("Execution time: " + 10e-9 * (stop-start));
} catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
}
It is because of the package comp2402a1. Java expects Part1 class file to be on the
comp2402a1 folder.
Create that folder and put the class file (runnning like $ java comp2402a1/Part1) or remove the package from the source code.
I was wondering if anyone has logic in java that removes duplicate lines while maintaining the lines order.
I would prefer no regex solution.
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
if (lines.add(uniqueLine = super.readLine()))
return uniqueLine;
return "";
}
//for testing..
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"test.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
if (strLine != "")
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Modified Version:
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
while (lines.add(uniqueLine = super.readLine()) == false); //read until encountering a unique line
return uniqueLine;
}
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"/home/emil/Desktop/ff.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
If you feed the lines into a LinkedHashSet, it ignores the repeated ones, since it's a set, but preserves the order, since it's linked. If you just want to know whether you've seena given line before, feed them into a simple Set as you go on, and ignore those which the Set already contains/contained.
It can be easy to remove duplicate line from text or File using new java Stream API. Stream support different aggregate feature like sort,distinct and work with different java's existing data structures and their methods. Following example can use to remove duplicate or sort the content in File using Stream API
package removeword;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;
import static java.nio.file.StandardOpenOption.*;
import static java.util.stream.Collectors.joining;
public class Java8UniqueWords {
public static void main(String[] args) throws IOException {
Path sourcePath = Paths.get("C:/Users/source.txt");
Path changedPath = Paths.get("C:/Users/removedDouplicate_file.txt");
try (final Stream<String> lines = Files.lines(sourcePath )
// .map(line -> line.toLowerCase()) /*optional to use existing string methods*/
.distinct()
// .sorted()) /*aggregrate function to sort disctincted line*/
{
final String uniqueWords = lines.collect(joining("\n"));
System.out.println("Final Output:" + uniqueWords);
Files.write(changedPath , uniqueWords.getBytes(),WRITE, TRUNCATE_EXISTING);
}
}
}
Read the text file using a BufferedReader and store it in a LinkedHashSet. Print it back out.
Here's an example:
public class DuplicateRemover {
public String stripDuplicates(String aHunk) {
StringBuilder result = new StringBuilder();
Set<String> uniqueLines = new LinkedHashSet<String>();
String[] chunks = aHunk.split("\n");
uniqueLines.addAll(Arrays.asList(chunks));
for (String chunk : uniqueLines) {
result.append(chunk).append("\n");
}
return result.toString();
}
}
Here's some unit tests to verify ( ignore my evil copy-paste ;) ):
import org.junit.Test;
import static org.junit.Assert.*;
public class DuplicateRemoverTest {
#Test
public void removesDuplicateLines() {
String input = "a\nb\nc\nb\nd\n";
String expected = "a\nb\nc\nd\n";
DuplicateRemover remover = new DuplicateRemover();
String actual = remover.stripDuplicates(input);
assertEquals(expected, actual);
}
#Test
public void removesDuplicateLinesUnalphabetized() {
String input = "z\nb\nc\nb\nz\n";
String expected = "z\nb\nc\n";
DuplicateRemover remover = new DuplicateRemover();
String actual = remover.stripDuplicates(input);
assertEquals(expected, actual);
}
}
Here's another solution. Let's just use UNIX!
cat MyFile.java | uniq > MyFile.java
Edit: Oh wait, I re-read the topic. Is this a legal solution since I managed to be language agnostic?
For better/optimum performance, it's wise to use Java 8's API features viz. Streams & Method references with LinkedHashSet for Collection as below:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
public class UniqueOperation {
private static PrintWriter pw;
enter code here
public static void main(String[] args) throws IOException {
pw = new PrintWriter("abc.txt");
for(String p : Files.newBufferedReader(Paths.get("C:/Users/as00465129/Desktop/FrontEndUdemyLinks.txt")).
lines().
collect(Collectors.toCollection(LinkedHashSet::new)))
pw.println(p);
pw.flush();
pw.close();
System.out.println("File operation performed successfully");
}
here I'm using a hashset to store seen lines
Scanner scan;//input
Set<String> lines = new HashSet<String>();
StringBuilder strb = new StringBuilder();
while(scan.hasNextLine()){
String line = scan.nextLine();
if(lines.add(line)) strb.append(line);
}
I have a requirement, for example, there will be number of .txt files in one loation c:\onelocation. I want to write the content to another location in txt format. This part is pretty easy and straight forward. But there is speed breaker here.
There will be time interval take 120 seconds. Read the files from above location and write it to another files with formate txt till 120secs and save the file with name as timestamp.
After 120sec create one more files with that timestamp but we have to read the files were cursor left in previous file.
Please can you suggest any ideas, if code is provided that would be also appreciable.
Thanks Damu.
How about this? A writer that automatically changes where it is writing two every 120 seconds.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeBoxedWriter extends Writer {
private static DateFormat FORMAT = new SimpleDateFormat("yyyyDDDHHmm");
/** Milliseconds to each time box */
private static final int TIME_BOX = 120000;
/** For testing only */
public static void main(String[] args) throws IOException {
Writer w = new TimeBoxedWriter(new File("."), "test");
// write one line per second for 500 seconds.
for(int i = 0;i < 500;i++) {
w.write("testing " + i + "\n");
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
w.close();
}
/** Output folder */
private File dir_;
/** Timestamp for current file */
private long stamp_ = 0;
/** Stem for output files */
private String stem_;
/** Current output writer */
private Writer writer_ = null;
/**
* Create new output writer
*
* #param dir
* the output folder
* #param stem
* the stem used to generate file names
*/
public TimeBoxedWriter(File dir, String stem) {
dir_ = dir;
stem_ = stem;
}
#Override
public void close() throws IOException {
synchronized (lock) {
if (writer_ != null) {
writer_.close();
writer_ = null;
}
}
}
#Override
public void flush() throws IOException {
synchronized (lock) {
if (writer_ != null) writer_.flush();
}
}
private void rollover() throws IOException {
synchronized (lock) {
long now = System.currentTimeMillis();
if ((stamp_ + TIME_BOX) < now) {
if (writer_ != null) {
writer_.flush();
writer_.close();
}
stamp_ = TIME_BOX * (System.currentTimeMillis() / TIME_BOX);
String time = FORMAT.format(new Date(stamp_));
writer_ = new FileWriter(new File(dir_, stem_ + "." + time
+ ".txt"));
}
}
}
#Override
public void write(char[] cbuf, int off, int len) throws IOException {
synchronized (lock) {
rollover();
writer_.write(cbuf, off, len);
}
}
}
Use RamdomAccessFile in java to move the cursor within the file.
Before start copying check the file modification/creation(in case of new files) time, if less than 2 mins then only start copying or else skip it.
Keep a counter of no.of bytes/lines read for each file. move the cursor to that position and read it from there.
You can duplicate the file rather than using reading and writing operations.
sample code:
FileChannel ic = new FileInputStream("<source file location>")).getChannel();
FileChannel oc = new FileOutputStream("<destination location>").getChannel();
ic.transferTo(0, ic.size(), oc);
ic.close();
oc.close();
HTH
File io is simple in java, here is an example I found on the web of copying a file to another file.
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}