As we all know, or might know, MediaFire does not allow direct download links, but you actually have to click the Download button to generate a random link that refers to the file. Is there a way to fetch that link and download it?
In despair of writing an auto-updating application, I have written a short Java application which allows the download of files from MediaFire. Here is the full code:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class mainwindow {
/**
* Launch the application.
*/
static mainwindow thisInstance;
public static void main(String[] args) {
new mainwindow();
}
public mainwindow()
{
otherthread();
}
public void otherthread()
{
navigate("http://www.mediafire.com/download/aqtmhwvb8yvqclu/SmartSharePC.jar","downloadedFromMediafire");
// navigate("http://www.mediafire.com/download/j7e4wh6hbdhdj84/Minecraft+1.5.2-+C.H.T.zip","mediafire");
}
private void navigate(String url,String sufix)
{
try
{
String downloadLink = fetchDownloadLink(getUrlSource(url));
saveUrl(downloadLink,sufix);
} catch (Exception e)
{
e.printStackTrace();
}
}
public void saveUrl(final String urlString,String sufix) throws Exception
{
System.out.println("Downloading...");
String filename = urlString.substring(urlString.lastIndexOf("/")+1, urlString.lastIndexOf("."))+"_"+sufix+urlString.substring(urlString.lastIndexOf("."), urlString.length());
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
System.out.println("Success!");
}
private static String getUrlSource(String url) throws IOException
{
System.out.println("Connecting...");
URL yahoo = new URL(url);
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream(), "UTF-8"));
String inputLine;
String total="";
while ((inputLine = in.readLine()) != null)
total+=inputLine;
in.close();
return total;
}
private static String fetchDownloadLink(String str)
{
System.out.println("Fetching download link");
try {
String regex = "(?=\\<)|(?<=\\>)";
String data[] = str.split(regex);
String found = "NOTFOUND";
for (String dat : data) {
if (dat.contains("DLP_mOnDownload(this)")) {
found = dat;
break;
}
}
String wentthru = found.substring(found.indexOf("href=\"") + 6);
wentthru = wentthru.substring(0, wentthru.indexOf("\""));
return wentthru;
} catch (Exception e)
{
e.printStackTrace();
return "ERROR";
}
}
}
Related
I'm writing a code where in data in a file has to be replaced with another file content.
I know how to use a string Replace() function. but the problem here is, I want to replace a string with a entirely new Data.
I'm able to append(in private static void writeDataofFootnotes(File temp, File fout)) the content, but unable to know how do I replace it.
Below is my code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
public class BottomContent {
public static void main(String[] args) throws Exception {
String input = "C:/Users/u0138039/Desktop/Proview/TEST/Test/src.html";
String fileName = input.substring(input.lastIndexOf("/") + 1);
URL url = new URL("file:///" + input);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
File fout = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/" + fileName);
File temp = new File("C:/Users/u0138039/Desktop/TEST/Test/OP/temp.txt");
if (!fout.exists()) {
fout.createNewFile();
}
if (!temp.exists()) {
temp.createNewFile();
}
FileOutputStream fos = new FileOutputStream(fout);
FileOutputStream tempOs = new FileOutputStream(temp);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
BufferedWriter tempWriter = new BufferedWriter(new OutputStreamWriter(tempOs));
String inputLine;
String footContent = null;
int i = 0;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("class=\"para\" id=\"")) {
footContent = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"<div class=\"tr_footnote\">\n<div class=\"footnote\">\n<sup><a name=\"ftn.$2\" href=\"#f$2\" class=\"tr_ftn\">$4</a></sup>\n"
+ "<div class=\"para\">" + "$6" + "\n</div>\n</div>\n</div>");
inputLine = inputLine.replaceAll(
"<p class=\"para\" id=\"(.*)_(.*)\" style=\"text-indent: (.*)%;\">(.*)(.)(.*)</p>",
"");
tempWriter.write(footContent);
tempWriter.newLine();
}
inputLine = inputLine.replace("</body>", "<hr/></body>");
bw.write(inputLine);
bw.newLine();
}
tempWriter.close();
bw.close();
in.close();
writeDataofFootnotes(temp, fout);
}
private static void writeDataofFootnotes(File temp, File fout) throws IOException {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(temp);
fw = new FileWriter(fout, true);
int c = fr.read();
while (c != -1) {
fw.write(c);
c = fr.read();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
// ...
}
}
}
Here I'm searching for a particular string and saving it in a separate txt file. And once I'm done with the job. I want to replace the <hr /> tag with the entire txt file data.
How can I achieve this?
I'd modify your processing loop as follows:
while ((inputLine = in.readLine()) != null) {
// Stop translation when we reach end of document.
if (inputLine.contains("</body>") {
break;
}
if (inputLine.contains("class=\"para\" id=\"")) {
// No changes in this block
}
bw.write(inputLine);
bw.newLine();
}
// Close temporary file
tempWriter.close();
// Open temporary file, and copy verbatim to output
BufferedReader temp_in = Files.newBufferedReader(temp.toPath());
String footnotes;
while ((footnotes = temp_in.readLine()) != null) {
bw.write(footnotes);
bw.newLine();
}
temp_in.close();
// Finish document
bw.write(inputLine);
bw.newLine();
while ((inputLine = in.readLine()) != null) {
bw.write(inputLine);
bw.newLine();
}
// ... and close all open files
I have some specific code that I need, to be able to have certain I/O stuff that I don't want to write every time, and I just want to be able to add a java class so that it already has that code in there, I tried doing :
/*
ID: my_id
PROG: ${filename}
LANG: JAVA
*/
import java.util.*;
import java.io.*;
import java.net.InetAddress;
public class ${filename} {
static class InputReader {
private StringTokenizer st = null;
private BufferedReader br = null;
public InputReader(String fileName) throws Exception {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public InputReader(InputStream in) {
try {
br = new BufferedReader(new InputStreamReader(in), 32768);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
boolean isLocal = hostname.equals("paulpc");
String location = null;
InputReader in = null;
PrintWriter out = null;
if (!isLocal) {
location = ${filename}.class.getProtectionDomain().getCodeSource().getLocation().getPath();
in = new InputReader(location + "/" + "${filename}.in");
out = new PrintWriter(new FileWriter(location + "/" + "${filename}.out"));
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
solve(in, out);
out.close();
}
public static void solve(InputReader in, PrintWriter out) {
}
}
Basically this thing needs to be in xml, but I don't know how to write it properly, I thought writing ${filename} everywhere would do it, but it doesn't work. All in all, I want the name of the file to be written in places where I write "${filename}", how can I do it?
You can declare a template variable like this:
public class ${cursor}${type:newName} {
public ${type}() {
// constructor
}
}
Now if you use this as a template, both type occurrences will be updated by what you write when you edit it after template insertion.
I want to download WordPress with Java.
My code looks like this:
public void file(String surl, String pathToSave) throws IOException {
URL url = new URL(surl);
sun.net.www.protocol.http.HttpURLConnection con = (HttpURLConnection) url.openConnection();
try (InputStream stream = con.getInputStream()) {
Files.copy(stream, Paths.get(pathToSave));
}
}
I am using this url to download the latest version of WordPress: http://wordpress.org/latest.tar.gz
But when I try extracting the tar.gz file I get an error saying the file is not in a gzip format.
I read this Issues uncompressing a tar.gz file and it looks like when I download WordPress I need to have a cookie enabled to accept the terms and services.
How would I do this?
Or am I incorrectly downloading the tar.gz file?
Here is what my tar.gz extracting code:
public class Unzip {
public static int BUFFER = 2048;
public void tar(String pathToTar, String outputPath) throws IOException {
File tarFile = new File(pathToTar);
TarArchiveInputStream tarInput =
new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(tarFile)));
TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
while(currentEntry != null) {
if (currentEntry.isDirectory()) {
File f = new File(outputPath + currentEntry.getName());
f.mkdirs();
}
else {
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(outputPath
+ currentEntry.getName());
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
while ((count = tarInput.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.close();
}
}
}
}
Thanks in advance.
Change sun.net.www.protocol.http.HttpURLConnection to java.net.HttpURLConnection
Add fos.close() after dest.close()
You must call currentEntry = tarInput.getNextTarEntry(); inside the while loop, too.
There is nothing with cookie enabled or accept the terms and services.
Here is my complete code.
Please try this and compare it to your code:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
public class Downloader {
public static final int BUFFER = 2048;
private void download(String surl, String pathToSave) throws IOException {
URL url = new URL(surl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try (InputStream stream = con.getInputStream()) {
Files.copy(stream, Paths.get(pathToSave));
}
}
private void unGz(String pathToGz, String outputPath) throws IOException {
FileInputStream fin = new FileInputStream(pathToGz);
BufferedInputStream in = new BufferedInputStream(fin);
try (FileOutputStream out = new FileOutputStream(outputPath)) {
try (GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in)) {
final byte[] buffer = new byte[BUFFER];
int n = 0;
while (-1 != (n = gzIn.read(buffer))) {
out.write(buffer, 0, n);
}
}
}
}
public void unTarGz(String pathToTar, String outputPath) throws IOException {
File tarFile = new File(pathToTar);
TarArchiveInputStream tarInput
= new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(tarFile)));
TarArchiveEntry currentEntry;
while ((currentEntry = tarInput.getNextTarEntry()) != null) {
if (currentEntry.isDirectory()) {
File f = new File(outputPath + currentEntry.getName());
f.mkdirs();
} else {
int count;
byte data[] = new byte[BUFFER];
try (FileOutputStream fos = new FileOutputStream(outputPath
+ currentEntry.getName())) {
try (BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER)) {
while ((count = tarInput.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
}
}
}
}
}
public static void main(String[] args) throws IOException {
Downloader down = new Downloader();
down.download("https://wordpress.org/latest.tar.gz", "/tmp/latest.tar.gz");
down.unTarGz("/tmp/latest.tar.gz", "/tmp/untar/");
}
}
This question already has an answer here:
StreamCorruptedException: invalid type code: AC
(1 answer)
Closed 5 years ago.
I am having the same issue as describe in:
https://stackoverflow.com/questions/17196588/java-io-streamcorruptedexception-invalid-type-code-ac-client-server
However, I do not see how I am creating multiple ObjectOutputStream. I am sure the OP received the correct answer and I am sure i am SOMEHOW creating multiple instances, but I don't see how.
public class Node {
public static void main(String[] args)
{
File file = new File("hotwords.txt");
AppendableObjectOutputStream oos = null;
OutputStream outStream = null;
long fileSize = file.length();
ArrayList<String> hotwords = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String CurrentLine;
while (( CurrentLine = br.readLine()) != null) {
hotwords.add(CurrentLine);
System.out.println("HOTWORD: " + CurrentLine);
}
br.close();
}
catch(Exception e) {
e.printStackTrace();
System.exit(0);
}
Socket s = null;
try{
s = new Socket("server", 8189);
PrintWriter writer = new PrintWriter(s.getOutputStream(), true);
writer.println("NODE");
outStream = s.getOutputStream();
oos = new AppendableObjectOutputStream(outStream);
oos.flush();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
try{
String os = System.getProperty("os.name").toLowerCase();
File logs;
if(os.matches("windows"))
{
logs = new File(".../logs");
System.out.println("Opening windows directory");
}
else
{
logs = new File("...logs");
System.out.println("Opening linux directory");
}
for( File f : logs.listFiles() )
{
if(f.getName().matches("machine.log"))
//if(f.getName().matches(".*log$"))
{
System.out.println("FOUND LOG " + f);
Runnable r = new FileHandler(s, oos, f, hotwords, file, fileSize);
Thread t = new Thread(r);
t.start();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
FileHandler.java /* This will create a thread for a log file to continuously read through it*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
public class FileHandler implements Runnable {
Socket c;
File file;
ArrayList<String> hotwords;
long hws;
File hwf;
AppendableObjectOutputStream oos;
public FileHandler(Socket conn, AppendableObjectOutputStream oos , File f, ArrayList<String> h, File hotwordFile, long hotwordSize)
{
c=conn;
file=f;
hotwords = h;
hws = hotwordSize;
hwf=hotwordFile;
this.oos = oos;
}
public void run()
{
System.out.println("FILEHANDLER:THREAD STARTED");
String sCurrentLine;
BufferedReader br = null;
try {
br = new BufferedReader( new FileReader(file) );
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
HashMap<String, LinkedHashSet<String> > temp = new HashMap<String, LinkedHashSet<String> >();
temp.put("FILEMON", new LinkedHashSet<String>() );
try {
//OutputStream outStream = c.getOutputStream();
//AppendableObjectOutputStream oos = new AppendableObjectOutputStream(outStream); moved to cache node so everyone share same output stream
boolean test = true;
while(test)
{
if(hwf.length() != hws)
{
hws = hwf.length();
hotwords.clear();
try
{
BufferedReader hbr = new BufferedReader(new FileReader(file));
String CurrentLine;
while (( CurrentLine = hbr.readLine()) != null) {
hotwords.add(CurrentLine);
System.out.println("HOTWORD: " + CurrentLine);
}
hbr.close();
}
catch(Exception e) {
e.printStackTrace();
System.exit(0);
}
}
while((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
for( String h : hotwords)
{
if( sCurrentLine.matches(h) )
{
System.out.println("FILEHANDLER:FOUND MATCHING LINE " + sCurrentLine);
temp.get("FILEMON").add(file.getName() + ": " + sCurrentLine);
break;
}
}
}
if(!temp.get("FILEMON").isEmpty())
{
if(c.isConnected())
{ oos.writeObject(temp); oos.reset(); }
System.out.println("NODE:PRINTED OBJECT: Size of FILEMON " + temp.get("FILEMON").size() + " with id: " + temp.toString());
temp.get("FILEMON").clear();
System.out.print("NODE:SIZE OF FILEMON AFTER CLEAR: " + temp.get("FILEMON").size());
}
}
br.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Hub.java /*This is a hub that runs on a seperate machine which recieves data from nodes*/
public class CacheMonitorHub {
public static void main(String[] args)
{
Map<Socket, AppendableObjectOutputStream> clients = Collections.synchronizedMap(new HashMap<Socket, AppendableObjectOutputStream>());
try
{
ServerSocket s = new ServerSocket(8189);
while(true)
{
Socket incoming = s.accept();
System.out.println("Spawning " + incoming);
Runnable r = new ConnectionHandler(incoming, clients);
Thread t = new Thread(r);
t.start();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Handler.java /*Lastly, this is responsible for publishing messages to clients*/
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ConnectionHandler implements Runnable {
Map<Socket, AppendableObjectOutputStream> Sockets;
Socket incoming;
public ConnectionHandler(Socket socket, Map<Socket, AppendableObjectOutputStream> others)
{
incoming = socket;
Sockets = others;
}
public void run()
{
InputStream inStream = null;
OutputStream outStream = null;
ObjectInputStream ois= null;
AppendableObjectOutputStream oos =null;
try{
inStream = incoming.getInputStream();
outStream = incoming.getOutputStream();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Creating Scanner..");
Scanner in = new Scanner(inStream);
//PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);
String clientOrNode = "";
clientOrNode = in.nextLine();
System.out.println("HUB: " + clientOrNode);
if(clientOrNode.equals("CLIENT"))
{
System.out.println("HUB:FOUND A CLIENT!");
/*
AppendableObjectOutputStream oos = null;
try{
oos = new AppendableObjectOutputStream(outStream);
}
catch(IOException e)
{
e.printStackTrace();
System.exit(0);
}
*/
try{
oos = new AppendableObjectOutputStream(outStream);
}
catch(IOException e)
{
e.printStackTrace();
}
Sockets.put(incoming, oos);
}
else if ( clientOrNode.equals("NODE") )
{
try {
ois = new ObjectInputStream(inStream);
}
catch(IOException e){
e.printStackTrace();
}
System.out.println("HUB:FOUND A NODE!");
System.out.println("HUB:ABOUT TO ENTER WHILE");
while(1==1)
{
try{
System.out.println("HUB:IN WHILE LOOP ABOUT TO READ OBJECT");
HashMap<String, LinkedHashSet<String>> temp = null;
try {
temp = (HashMap<String, LinkedHashSet<String>>) ois.readObject();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("HUB:OBJECT RECIEVED " + temp.toString());
for(Socket s : Sockets.keySet())
{
System.out.println("HUB:WRITING OBJECT NOW TO " + s.toString());
try {
Sockets.get(s).writeObject(temp);
Sockets.get(s).reset();
}
catch(Exception e)
{
Sockets.remove(s);
}
}
System.out.println("PAST FOR LOOP!!");
}
catch(Exception e)
{
e.printStackTrace();
}
try {
Thread.sleep(200);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
AppendableObjectOutputStream /*Just tried adding this as seen on suggestion from other post but not helping*/
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.IOException;
public class AppendableObjectOutputStream extends ObjectOutputStream {
public AppendableObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
#Override
protected void writeStreamHeader() throws IOException {
// do not write a header, but reset:
// this line added after another question
// showed a problem with the original
reset();
}
}
Any ideas as to why I am getting java.io.StreamCorruptedException: invalid type code: AC?
Unless the FileHandler.run()method is synchronized, or there is internal synchronization within it, neither of which is true, I don't see how you can possibly expect this to work. You're writing to the same ObjectOutputStream from multiple threads: you're going to get interleaving of data. Anything could happen at the receiver.
NB testing isConnected() doesn't accomplish anything useful. You did connect the Socket, when you created it, and isConnected() will continue to tell you so, even after you close it. It doesn't for example tell you whether the connection is still alive.
I've got a program where I need to generate an integer, write it to a text file and read it back the next time the program runs. After some anomalous behavior, I've stripped it down to setting an integer value, writing it to a file and reading it back for debugging.
totScore, is set to 25 and when I print to the console prior to writing to the file, I see a value of 25. However, when I read the file and print to the console I get three values...25, 13, and 10. Viewing the text file in notepad gives me a character not on the keyboard, so I suspect that the file is being stored in something other that int.
Why do I get different results from my write and read steps?
Is it not being written as an int? How are these values being stored in the file? Do I need to cast the read value as something else and convert it to an integer?
Consider:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.file.*;
import java.nio.file.StandardOpenOption.*;
//
public class HedgeScore {
public static void main(String[] args) {
int totScore = 25;
OutputStream outStream = null; ///write
try {
System.out.println("totscore="+totScore);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("hedgescore.txt")));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
bw.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
try {
InputStream input = new FileInputStream("hedgescore.txt");
int data = input.read();
while(data != -1) {
System.out.println("data being read from file :"+ data);
data = input.read();
int prevScore = data;
}
input.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
}
}
You're reading/writing Strings and raw data, but not being consistent. Why not instead read in Strings (using a Reader of some sort) and then convert to int by parsing the String? Either that or write out your data as bytes and read it in as bytes -- although that can get quite tricky if the file must deal with different types of data.
So either:
import java.io.*;
public class HedgeScore {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
BufferedWriter bw = null;
try {
System.out.println("totscore=" + totScore);
bw = new BufferedWriter(new FileWriter(new File(
FILE_PATH)));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
InputStream input = null;
try {
input = new FileInputStream(FILE_PATH);
int data = 0;
while ((data = input.read()) != -1) {
System.out.println("data being read from file :" + data);
}
input.close();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
or:
import java.io.*;
public class HedgeScore2 {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
PrintWriter pw = null;
try {
System.out.println("totscore=" + totScore);
pw = new PrintWriter(new FileWriter(new File(FILE_PATH)));
pw.write(String.valueOf(totScore));
pw.write(System.getProperty("line.separator"));
pw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (pw != null) {
pw.close();
}
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(FILE_PATH));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}