Using File Dialogue Box Rather than FilePath Java - java

New to Java - I am trying to import a .txt file containing integers.
Eventually I want to import the integers into an arraylist and then create a frequency distribution and calculate the average.
Currently I am struggling to use the file dialogue box which is my end goal. I can import the .txt using the file path in my code shown. If any one could help me out with how to use the dialogue box instead it would be greatly appreciated!
import java.io.*;
import java.util.*;
public class Distribution {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Enter a complete file path to file you would like to open:");
String fileName = input.nextLine();
File inFile = new File(fileName);
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
}
}
catch (Exception e) {
System.out.println(e);
}
finally {
try {
ins.close();
}
catch (Exception e) {
}
}
} // main end
}

Well, It's simple and easy.
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
class DistributionUI {
public static void main(String[] args) {
System.out.println("Enter a complete file path to file you would like to open:");
final JFileChooser fchooser = new JFileChooser() {
private static final long serialVersionUID = 1L;
public void approveSelection() {
File inFile = getSelectedFile();
if (inFile.exists() ) {
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
ins.close();
} catch (Exception e) {
}
}
}
super.approveSelection();
}
};
fchooser.setCurrentDirectory(new File("."));
fchooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter("my file", "txt");
fchooser.addChoosableFileFilter(filter);
fchooser.showOpenDialog(null);
} // main end
}

Related

Java getting input from USB Barcode scanner

I have Honeywell USB barcode scanner. I want to read input of barcode scanner by using Java code.
I got solution by below code but i dont want to use any gui.
import java.awt.AWTEvent;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class BarcodeScaner extends JFrame {
private static String strBarcode = "";
private static JTextField jtBarcode = new JTextField(25);
public BarcodeScaner() {
getContentPane().setLayout(new FlowLayout());
getContentPane().add(new JLabel("Capture barcode "));
getContentPane().add(jtBarcode);
}
public static void main(String[] args) {
BarcodeScaner br = new BarcodeScaner();
readBarCode();
br.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
br.setVisible(true);
br.pack();
}
private static void readBarCode() {
// start of listening for barcode events
Toolkit.getDefaultToolkit().addAWTEventListener(new BarcodeAwareAWTEventListener(new BarcodeCapturedListener() {
#Override
public void barcodeCaptured(String barcode) {
strBarcode = barcode;
System.out.println("====="+barcode);
jtBarcode.setText(strBarcode);
}
}), AWTEvent.KEY_EVENT_MASK);
// end of listening for barcode events
}
}
In above code i have to focus on textbox then only i get scanned value.
I have search in stackoverflow but i didnt get any specific solution.
I also try this below code but still serialEvent is not execute.
package scanhandler;
import java.awt.AWTException;
import java.awt.Robot;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Enumeration;
import java.util.Properties;
import java.util.TooManyListenersException;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
public class ScanHandler implements Runnable, SerialPortEventListener {
private static CommPortIdentifier myCommPortIdentifier;
private static Enumeration portList;
private static String TimeStamp;
private static String driverClass;
private static String connectionString;
private static String comPort;
private Connection myConnection;
private InputStream myInputStream;
private Robot myRobot;
private SerialPort mySerialPort;
private Thread myThread;
public ScanHandler() {
// open serial port
try {
TimeStamp = new java.util.Date().toString();
mySerialPort = (SerialPort) myCommPortIdentifier.open("ComControl", 2000);
//System.out.println(TimeStamp + ": " + myCommPortIdentifier.getName() + " opened for scanner input");
} catch (PortInUseException e) {
e.printStackTrace();
}
// get serial input stream
try {
myInputStream = mySerialPort.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
// add an event listener on the port
try {
mySerialPort.addEventListener(this);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
mySerialPort.notifyOnDataAvailable(true);
// set up the serial port properties
try {
mySerialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
mySerialPort.setDTR(false);
mySerialPort.setRTS(false);
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
// make a robot to pass keyboard data
try {
myRobot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
// create the thread
myThread = new Thread(this);
myThread.start();
}
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
// on scan
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
StringBuilder myStringBuilder = new StringBuilder();
int c;
try {
// append the scanned data onto a string builder
while ((c = myInputStream.read()) != 10){
if (c != 13) myStringBuilder.append((char) c);
}
// send to keyboard buffer if it the barcode doesn't start with '5'
if (myStringBuilder.charAt(0) != '5') {
for (int i = 0; i < myStringBuilder.length(); i++) {
myRobot.keyPress((int) myStringBuilder.charAt(i));
myRobot.keyRelease((int) myStringBuilder.charAt(i));
}
// here's the scanned barcode as a variable!
} else {
TimeStamp = new java.util.Date().toString();
System.out.println(TimeStamp + ": scanned input received:" + myStringBuilder.toString());
}
// close the input stream
myInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// read ScanHandler properties
Properties myProperties = new Properties();
try {
myProperties.load(new FileInputStream("config.properties"));
comPort = myProperties.getProperty("ScanHandler.comPort");
} catch (IOException e) {
e.printStackTrace();
}
try {
// get our pre-defined COM port
myCommPortIdentifier = CommPortIdentifier.getPortIdentifier(comPort);
ScanHandler reader = new ScanHandler();
} catch (Exception e) {
TimeStamp = new java.util.Date().toString();
System.out.println(TimeStamp + ": " + comPort + " " + myCommPortIdentifier);
System.out.println(TimeStamp + ": msg1 - " + e);
}
};
}
Please set the scanner to USB Serial mode by using the setting barcode stated in the user's guide.
Then install the serial port device driver of the OS of the machine to which the scanner is connected.
Then you can open the serial port and send commands to the scanner and receive barcode data.

Why downloading image file using input-output stream results broken image files in Java?

I am reading a book on java concurrency in which there is an example of downloading image file from internet. The program uses Files.copy() built-in function to download the image file. Code:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.TimeUnit;
public class TwoFileDownloadingWithJoin {
public static void main(String[] args) {
Thread beatPrinter = new BeatPrinter();
Thread down1 = new FileDownloader("https://secure.meetupstatic.com/photos/event/e/9/f/9/600_464039897.jpeg", "meet1.jpg");
Thread down2 = new FileDownloader("https://secure.meetupstatic.com/photos/event/2/d/0/f/600_464651535.jpeg", "meet2.jpg");
beatPrinter.setName("Beat Printer");
down1.setName("file1 downloader");
down2.setName("file2 downloader");
try {
down1.start();
down2.start();
TimeUnit.MILLISECONDS.sleep(100);
beatPrinter.start();
down1.join();
down2.join();
((BeatPrinter) beatPrinter).kill();
beatPrinter.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Download Complete");
}
}
class BeatPrinter extends Thread {
private volatile boolean live = true;
#Override
public void run() {
while (live) {
printStar("Downloading ");
}
}
void kill() {
live = false;
}
private void printStar(String msg) {
System.out.print(msg);
char[] signs = {'-', '\\', '|', '/'};
for (char s : signs) {
System.out.print(s);
try {
Thread.sleep(300);
System.out.print('\b');
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < msg.length(); i++)
System.out.print('\b');
}
}
class FileDownloader extends Thread {
private String url;
private String fileName;
FileDownloader(String url, String fileName) {
this.url = url;
this.fileName = fileName;
}
#Override
public void run() {
File destinationFile = new File(fileName);
try {
System.out.println("Starting download of " + fileName);
URL fileUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
Files.copy(inputStream, destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
inputStream.close();
} else {
System.out.println("Error: " + connection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have modified the program as follows to show download progress:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class TwoFileDownloadingWithJoin {
public static void main(String[] args) {
Thread down1 = new FileDownloader("https://secure.meetupstatic.com/photos/event/e/9/f/9/600_464039897.jpeg", "meet1.jpg");
Thread down2 = new FileDownloader("https://secure.meetupstatic.com/photos/event/2/d/0/f/600_464651535.jpeg", "meet2.jpg");
down1.setName("file1 downloader");
down2.setName("file2 downloader");
try {
down1.start();
down2.start();
TimeUnit.MILLISECONDS.sleep(100);
down1.join();
down2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Download Complete");
}
}
class FileDownloader extends Thread {
private String url;
private String fileName;
private double totRead;
private ProgressUpdater progressUpdater;
FileDownloader(String url, String fileName) {
this.url = url;
this.fileName = fileName;
this.progressUpdater = new ProgressUpdater(this, fileName);
}
double getTotRead() {
return totRead;
}
#Override
public void run() {
File destinationFile = new File(fileName);
try {
System.out.println("Starting download of " + fileName);
URL fileUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
double fileSize = Double.parseDouble(connection.getHeaderField("content-length"));
InputStream fis = connection.getInputStream();
FileOutputStream fos = new FileOutputStream(destinationFile);
byte[] buffer = new byte[1024];
double currRead;
double totSize = fileSize / 1024.0;
progressUpdater.setTotSize(totSize);
progressUpdater.start();
while ((currRead = fis.read(buffer)) != -1) {
fos.write(buffer);
totRead += currRead / 1024;
}
fis.close();
fos.close();
progressUpdater.kill();
progressUpdater.join();
} else {
System.out.println("Error: " + connection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class ProgressUpdater extends Thread {
private FileDownloader fileDownloader;
private volatile boolean killed;
private String fileName;
private double totSize;
public ProgressUpdater(FileDownloader fileDownloader, String fileName) {
this.fileDownloader = fileDownloader;
this.fileName = fileName;
killed = false;
}
public void kill() {
killed = true;
}
public void setTotSize(double totSize) {
this.totSize = totSize;
}
#Override
public void run() {
boolean hundredPercent = false;
while (!killed || !hundredPercent) {
double totRead = fileDownloader.getTotRead();
System.out.println(String.format("%s: %.2fKB of %.2fKB downloaded(%.2f%%)", fileName, totRead, totSize, 100 * totRead / totSize));
hundredPercent = (100 * totRead / totSize) > 99.00;
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Instead of using Files.copy() I read bytes from input stream and then wrote the bytes to output file. But my approach results broken images. Where is the problem?
Original Image: https://secure.meetupstatic.com/photos/event/e/9/f/9/600_464039897.jpeg
Broken Image: https://imgur.com/UrgafA5

using method-declared variable in mutators?

Confused on the logic of getting a variable out of a method in a class and using it in a mutator.
Edit: here is my code dump
My Code:
package tests;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
public class LoadingBox extends JPanel {
String[] inFiles = new String[0];
public void loadIt(){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT FILES", "txt");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getCurrentDirectory();
String path = file.getPath();
String filename = chooser.getSelectedFile().getName();
String fullpath = path + "/" + filename;
}
}
public String[] getFiles() {
return inFiles;
}
public void setFiles(String[] inFiles) {
this.inFiles = inFiles;
}
}
Heres where it's going
package tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileScan {
ArrayList<String> stringArray = new ArrayList<String>();
ArrayList<Integer> numArray = new ArrayList<Integer>();
LoadingBox LoadFile = new LoadingBox();
String[] files = {LoadFile.getFiles()[0]};
//ITS GOING RIGHT HERE^^^^^^^^^^^^^^^
public void scan(String[] args) throws IOException {
Scanner input = null;
new FileScan();
try {
input = new Scanner(new File(files[0]));
//add strings and integers from file to different arrays
while (input.hasNext()) {
String token = input.nextLine();
try{
int o = Integer.parseInt(token);
numArray.add(o);
}
catch(NumberFormatException nfe){
stringArray.add(token);
}
}
}
finally {
if (input != null) {
input.close();
}
}
}
//Some more getters and setters down here
Stack overflow is making me type more so I'm going to ramble out some words down here so that I can post.
I don't know what the error you're getting is, so I'm just going to rewrite your code and hope it solves your problem.
package tests;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
public class LoadingBox extends JPanel {
private String inFiles;
public void loadIt(){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT FILES", "txt");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(getParent());
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getCurrentDirectory();
String path = file.getPath();
String filename = chooser.getSelectedFile().getName();
String fullpath = path + "/" + filename;
this.setFiles(fullpath);
}
}
public String getFiles() {
return inFiles;
}
public void setFiles(String inFiles) {
this.inFiles = inFiles;
}
}
package tests;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class FileScan {
private ArrayList<String> stringArray;
private ArrayList<Integer> numArray;
private LoadingBox loadFile;
private String files;
public FileScan(){
stringArray = new ArrayList<String>();
numArray = new ArrayList<Integer>();
loadFile = new LoadingBox();
loadFile.loadIt();
files = LoadFile.getFiles();
}
public void scan(String[] args) throws IOException {
Scanner input = null;
new FileScan();
try {
input = new Scanner(new File(files));
//add strings and integers from file to different arrays
while (input.hasNext()) {
String token = input.nextLine();
try{
int o = Integer.parseInt(token);
numArray.add(o);
}
catch(NumberFormatException nfe){
stringArray.add(token);
}
}
}
finally {
if (input != null) {
input.close();
}
}
}

NullPointException when I try to navigate forms on j2me using buttons

I'm having trouble linking the main page to the second page by the click of a button. It throws a NullPointException. Can someone please tell me where I've erred?
import java.io.InputStream;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
public class standings extends MIDlet implements ActionListener{
public Command cmdSelect;
public Form fform, selectLgform;
public Button btnSelectLeague,btnHelp,btnAbout,btnExit;
public TextArea taHome,taAbout, taHelp, taSelectLg;
private InputStream iStream;
private StringBuffer strBuffer;
private Form selectLgForm;
public void startApp() {
Display.init(this);
try {
Resources rs= Resources.open("/restheme.res");
UIManager.getInstance().setThemeProps(rs.getTheme("Theme2"));
} catch (Exception e) {
e.getMessage();
}
displayMainForm();
}
public void displayMainForm()
{
fform = new Form("Football League Standings");
taHome= new TextArea(5,20,TextArea.ANY);
fform.setLayout(new BorderLayout());
fform.setTransitionInAnimator(CommonTransitions.createFade(1000));
iStream = getClass().getResourceAsStream("/intro.txt");
strBuffer = new StringBuffer();
int next = 1;
try {
while((next = iStream.read()) != -1) {
char nextChar = (char) next;
strBuffer.append(nextChar);
}
} catch (IOException ex) {
ex.printStackTrace();
}
taHome.setText(strBuffer.toString());
strBuffer = null;
taHome.setFocusable(false);
taHome.setEditable(false);
taHome.setUIID("Label");
//fform.addComponent(BorderLayout.CENTER,taHome);
btnSelectLeague= (new Button("Select league"));
btnHelp= (new Button("Help"));
btnAbout= (new Button("About"));
btnExit= (new Button("Exit"));
Container mcont = new Container(new BoxLayout(BoxLayout.Y_AXIS));
mcont.addComponent(taHome);
mcont.addComponent(btnSelectLeague);
mcont.addComponent(btnHelp);
mcont.addComponent(btnAbout);
mcont.addComponent(btnExit);
fform.addComponent(BorderLayout.CENTER, mcont);
btnSelectLeague.addActionListener(this);
btnHelp.addActionListener(this);
btnAbout.addActionListener(this);
btnExit.addActionListener(this);
fform.show();
}
/* Command exitCommand = new Command("Exit");
fform.addCommand(exitCommand);
fform.addCommandListener(this);
}
}*/
public void selectLgForm()
{
selectLgForm= new Form("Select League");
taSelectLg= new TextArea(5,20,TextArea.ANY);
selectLgForm.setLayout(new BorderLayout());
selectLgForm.setTransitionInAnimator(CommonTransitions.createFade(1000));
iStream = getClass().getResourceAsStream("/selectlg.txt");
strBuffer = new StringBuffer();
int next = 1;
try {
while((next = iStream.read()) != -1) {
char nextChar = (char) next;
strBuffer.append(nextChar);
}
} catch (IOException ex) {
ex.printStackTrace();
}
taSelectLg.setText(strBuffer.toString());
strBuffer = null;
taSelectLg.setFocusable(false);
taSelectLg.setEditable(false);
taSelectLg.setUIID("Label");
selectLgForm.addComponent(BorderLayout.CENTER,taAbout);
//START OF MENU BUTTONS
selectLgForm.addCommand(new Command("Back")
{
public void actionPerformed(ActionEvent e)
{
displayMainForm();
}
});
selectLgForm.show();
}//END OF MENU BUTTONS
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==btnSelectLeague){
selectLgForm();
}
my best guesses are:
- selectLgForm.addComponent(BorderLayout.CENTER,taAbout) throws a NullPointerException because taAbout is null.
- or iStream = getClass().getResourceAsStream("/selectlg.txt"); throws a NullPointerException because the text file is not where you think it is.

Java textfile I/O problem

I have to make a torpedo game for school with a toplist for it. I want to store it in a folder structure near the JAR: /Torpedo/local/toplist/top_i.dat, where the i is the place of that score. The files will be created at the first start of the program with this call:
File f;
f = new File(Toplist.toplistPath+"/top_1.dat");
if(!f.exists()){
Toplist.makeToplist();
}
Here is the toplist class:
package main;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.prefs.Preferences;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Toplist {
static String toplistPath = "./Torpedo/local/toplist"; //I know it won't work this easily, it's only to get you the idea
public static JFrame toplistWindow = new JFrame("Torpedó - [TOPLISTA]");
public static JTextArea toplist = new JTextArea("");
static StringBuffer toplistData = new StringBuffer(3000);
public Toplist() {
toplistWindow.setSize(500, 400);
toplistWindow.setLocationRelativeTo(null);
toplistWindow.setResizable(false);
getToplist();
toplist.setSize(400, 400);
toplist.setLocation(0, 100);
toplist.setColumns(5);
toplist.setText(toplistData.toString());
toplist.setEditable(false);
toplist.setBackground(Color.WHITE);
toplistWindow.setLayout(null);
toplistWindow.setVisible(true);
}
public Toplist(Player winner) {
//this is to be done yet, this will set the toplist at first and then display it
toplistWindow.setLayout(null);
toplistWindow.setVisible(true);
}
/**
* Creates a new toplist
*/
public static void makeToplist(){
new File(toplistPath).mkdir();
for(int i = 1; i <= 10; i++){
File f = new File(toplistPath+"/top_"+i+".dat");
try {
f.createNewFile();
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista létrehozása", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* If the score is a top score it inserts it into the list
*
* #param score - the score to be checked
*/
public static void setToplist(int score, Player winner){
BufferedReader input = null;
PrintWriter output = null;
int topscore;
for(int i = 1; i <= 10; i++){
try {
input = new BufferedReader(new FileReader(toplistPath+"/top_"+i+",dat"));
String s;
topscore = Integer.parseInt(input.readLine());
if(score > topscore){
for(int j = 9; j >= i; j--){
input = new BufferedReader(new FileReader(toplistPath+"/top_"+j+".dat"));
output = new PrintWriter(new FileWriter(toplistPath+"/top_"+(j+1)+".dat"));
while ((s = input.readLine()) != null) {
output.println(s);
}
}
output = new PrintWriter(new FileWriter(toplistPath+"/top_"+i+".dat"));
output.println(score);
output.println(winner.name);
if(winner.isLocal){
output.println(Torpedo.session.remote.name);
}else{
output.println(Torpedo.session.remote.name);
}
output.println(Torpedo.session.mapName);
output.println(DateUtils.now());
break;
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista frissítése", "Error", JOptionPane.ERROR_MESSAGE);
}
}
if (output != null) {
output.close();
}
}
}
}
/**
* This loads the toplist into the buffer
*/
public static void getToplist(){
BufferedReader input = null;
toplistData = null;
String s;
for(int i = 1; i <= 10; i++){
try {
input = new BufferedReader(new FileReader(toplistPath+"/top_"+i+".dat"));
while((s = input.readLine()) != null){
toplistData.append(s);
toplistData.append('\t');
}
toplistData.append('\n');
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista betöltése", "Error", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(new JFrame(), "Fájl hiba: toplista betöltése", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
*
* #author http://www.rgagnon.com/javadetails/java-0106.html
*
*/
public static class DateUtils {
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
}
}
The problem is, that it can't access any of the files. I've tried adding them to the classpath and at least six different variations of file/path handling I found online but nothing worked.
Could anyone tell me what do I do wrong?
Thank you.
When you dealing with files, the path is relative to where you execute the application. When running it from eclipse, the base path is the project folder.
What you would normally do if the file doesn't exist is calling mkdirs() on the parent to create the folder hierarchy, then create the file.

Categories