sound file not playing - java

I am writing a game for a class and having trouble adding sound and images. We were given the framework from Andrew Davison's Killer Game Programming book to work with, and I feel like I am copying it exactly, but I am unable to play a sound file.
This is the SDLLoader class:
package zombieCity;
/* SDLLoader stores a collection of SDLInfo objects
in a HashMap whose keys are their names.
The name and filename for a line is obtained from a sounds
information file which is loaded when SDLLoader is created.
The information file is assumed to be in Sounds/.
SDLLoader allows a specified clip to be played, stopped,
resumed, looped. A SoundsWatcher can be attached to a clip.
All of this functionality is handled in the SDLInfo object;
SDLLoader simply redirects the method call to the right SDLInfo.
It is possible for many lines to play at the same time, since
each SDLInfo object is responsible for playing its clip.
*/
import java.util.*;
import java.io.*;
import javax.print.DocFlavor.URL;
public class SDLLoader
{
private final static String SOUND_DIR = "Sounds/";
private HashMap<String, SDLInfo> sdlMap;
/* The key is the clip 'name', the object (value)
is a SDLInfo object */
public SDLLoader(String soundsFnm)
{ sdlMap = new HashMap<String, SDLInfo>();
loadSoundsFile(soundsFnm);
}
public SDLLoader()
{ sdlMap = new HashMap<String, SDLInfo>(); }
private void loadSoundsFile(String soundsFnm)
/* The file format are lines of:
<name> <filename> // a single sound file
and blank lines and comment lines.
*/
{
String sndsFNm = SOUND_DIR + soundsFnm;
System.out.println("Reading file: " + sndsFNm);
try {
java.net.URL inFile = this.getClass().getResource("/Sounds/SDLInfo.txt");
System.out.println("url " + inFile);
InputStreamReader in = new InputStreamReader(inFile.openStream());
BufferedReader br = new BufferedReader(in);
StringTokenizer tokens;
String line, name, fnm;
while((line = br.readLine()) != null) {
if (line.length() == 0) // blank line
continue;
if (line.startsWith("//")) // comment
continue;
tokens = new StringTokenizer(line);
if (tokens.countTokens() != 2)
System.out.println("Wrong no. of arguments for " + line);
else {
name = tokens.nextToken();
fnm = tokens.nextToken();
load(name, fnm);
}
}
br.close();
}
catch (IOException e)
{ System.out.println("Error reading file: " + sndsFNm);
System.exit(1);
}
} // end of loadSoundsFile()
// ----------- manipulate a particular clip --------
public void load(String name, String fnm)
// create a SDLInfo object for name and store it
{
if (sdlMap.containsKey(name))
System.out.println( "Error: " + name + "already stored");
else {
sdlMap.put(name, new SDLInfo(name, fnm) );
System.out.println("-- " + name + "/" + fnm);
}
} // end of load()
public void close(String name)
// close the specified clip
{ SDLInfo si = (SDLInfo) sdlMap.get(name);
if (si == null)
System.out.println( "Error: " + name + "not stored");
else
si.close();
} // end of close()
public void play(String name, boolean toLoop)
// play (perhaps loop) the specified clip
{ SDLInfo si = (SDLInfo) sdlMap.get(name);
if (si == null)
System.out.println( "Error: " + name + "not stored");
else
si.beginPlayback(toLoop);
} // end of play()
public void stop(String name)
// stop the clip, resetting it to the beginning
{ SDLInfo si = (SDLInfo) sdlMap.get(name);
if (si == null)
System.out.println( "Error: " + name + "not stored");
else
si.stop();
} // end of stop()
// -------------------------------------------------------
public void setWatcher(String name, SoundsWatcher sw)
/* Set up a watcher for the clip. It will be notified when
the clip loops or stops. */
{ SDLInfo si = (SDLInfo) sdlMap.get(name);
if (si == null)
System.out.println( "Error: " + name + "not stored");
else
si.setWatcher(sw);
} // end of setWatcher()
} // end of ClipsLoader class
stack trace
fps: 100; period: 10 ms
Reading file: Sounds/SDLInfo.txt
url file:/C:/Documents%20and%20Settings/MyName/Desktop/java%20programs/Zombie%20City/bin/Sounds/SDLInfo.txt
Exception in thread "main" java.lang.NullPointerException
at com.sun.media.sound.StandardMidiFileReader.getSequence(Unknown Source)
at javax.sound.midi.MidiSystem.getSequence(Unknown Source)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at zombieCity.SDLInfo.loadLine(SDLInfo.java:35)
at zombieCity.SDLInfo.<init>(SDLInfo.java:27)
at zombieCity.SDLLoader.load(SDLLoader.java:95)
at zombieCity.SDLLoader.loadSoundsFile(SDLLoader.java:73)
at zombieCity.SDLLoader.<init>(SDLLoader.java:38)
at zombieCity.FlyingHero.simpleInitialize(FlyingHero.java:144)
at zombieCity.Frame.<init>(Frame.java:68)
at zombieCity.FlyingHero.<init>(FlyingHero.java:80)
at zombieCity.FlyingHero.main(FlyingHero.java:376)
error was being caught in this class:
package zombieCity;
/* Load a line, which can be played, stopped, resumed, looped.
An object implementing the SoundsWatcher interface
can be notified when the line loops or stops.
*/
import java.io.*;
import javax.sound.sampled.*;
public class SDLInfo implements LineListener, Runnable
{
private final static String SOUND_DIR = "Sounds/";
private String name, filename;
private SourceDataLine line = null;
private boolean isLooping = false;
private SoundsWatcher watcher = null;
private Thread soundPlayer;
public SDLInfo(String nm, String fnm)
{ name = nm;
filename = SOUND_DIR + fnm;
loadLine(filename);
} // end of SDLInfo()
private void loadLine(String fnm)
{
try {
// link an audio stream to the sound line's file
AudioInputStream stream = AudioSystem.getAudioInputStream(
getClass().getResource(fnm) );
AudioFormat format = stream.getFormat();
// convert ULAW/ALAW formats to PCM format
if ( (format.getEncoding() == AudioFormat.Encoding.ULAW) ||
(format.getEncoding() == AudioFormat.Encoding.ALAW) ) {
AudioFormat newFormat =
new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits()*2,
format.getChannels(),
format.getFrameSize()*2,
format.getFrameRate(), true); // big endian
// update stream and format details
stream = AudioSystem.getAudioInputStream(newFormat, stream);
System.out.println("Converted Audio format: " + newFormat);
format = newFormat;
}
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
// make sure sound system supports data line
if (!AudioSystem.isLineSupported(info)) {
System.out.println("Unsupported Line File: " + fnm);
return;
}
// get clip line resource
line = (SourceDataLine) AudioSystem.getLine(info);
// listen to line for events
line.addLineListener(this);
line.open(format); // open the sound file as a line
stream.close(); // we're done with the input stream
} // end of try block
catch (UnsupportedAudioFileException audioException) {
System.out.println("Unsupported audio file: " + fnm);
}
catch (LineUnavailableException noLineException) {
System.out.println("No audio line available for : " + fnm + " " + noLineException);
}
catch (IOException ioException) {
System.out.println("Could not read: " + fnm);
}
// catch (Exception e) {
// System.out.println("Problem with " + fnm);
// }
} // end of loadLine()
public void update(LineEvent lineEvent){}
// update() not used
public void close()
{ if (line != null) {
line.stop();
line.close();
}
}
public void beginPlayback(boolean toLoop)
{
if (line != null){
isLooping = toLoop;
if (soundPlayer == null) {
soundPlayer = new Thread(this);
soundPlayer.start();
}
}
}
public void play()
{
try{
if (line != null) {
int numRead = 0;
byte[] buffer = new byte[line.getBufferSize()];
AudioInputStream stream = AudioSystem.getAudioInputStream(getClass().getResource(filename) );
line.start();
// read and play chunks of the audio
int offset;
while ((numRead = stream.read(buffer,0,buffer.length)) >= 0) {
offset = 0;
while (offset < numRead)
offset += line.write(buffer, offset, numRead-offset);
}
// wait until all data is played, then stop the line
stream.close();
line.drain();
line.stop();
}
}
catch (IOException ioException) {
System.out.println("Could not read: " + filename);
}
catch (UnsupportedAudioFileException audioException) {
System.out.println("Unsupported audio file: " + filename);
}
} //end of play()
public void run()
{
do{ play();}while(isLooping);
}
public void stop()
// stop and reset line to its start
{ if (line != null) {
isLooping = false;
line.drain();
line.stop();
}
}
public void setWatcher(SoundsWatcher sw)
{ watcher = sw; }
// -------------- other access methods -------------------
public String getName()
{ return name; }
} // end of ClipInfo class

Have you tried it with a .wav file
if you need to comvert convert at
convert here

try adding the full sound file directory at
private final static String SOUND_DIR = "Sounds/";
Example dir
"C:/Stuff/Sounds/soundfile.wav
This May help you
here

Related

Multithread PDF manipulation

I'm writing a java program whose operation is summarized as follows:
The subfolder with the specified name is selected in the source
folder.
All the pdfs are taken and converted into txt files in
the target folder.
The name of an item is searched inside the
txt.
If the name is found then the pdf from source to target is
copied.
All the txt from the target folder are deleted, in this
way all the pdfs containing the searched word remain.
"It all works", the problem is that the txt files are not deleted from target and I can not understand why. Thanks in advance, best regards.
Launcher.java:
import java.lang.String;
import java.util.Scanner;
import java.io.File;
public class Launcher {
// campi
int status = 1;
static String source = "C:\\Users\\MyUser\\Desktop\\source\\";
static String target = "C:\\Users\\MyUser\\Desktop\\target\\";
public static void main(String [] args) {
// strings
String src = source;
String item = "";
// init
Scanner scan = new Scanner(System.in);
System.out.print("\nFornitore: ");
src += scan.nextLine().toUpperCase() + "\\";
System.out.print("Item: ");
item = scan.nextLine();
// notifier
Launcher launcher = new Launcher();
// threads
MakerThread maker = new MakerThread(launcher, src, target);
SearcherThread searcher = new SearcherThread(launcher, src, target, item);
CleanupThread cleaner = new CleanupThread(launcher, target);
// run
maker.start();
searcher.start();
cleaner.start();
}
}
MakerThread.java:
import java.io.File;
public class MakerThread extends Thread {
// campi
String src = "";
String target = "";
Launcher launcher;
// costruttore
public MakerThread(Launcher launcher, String src, String target) {
this.src = src;
this.target = target;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.src);
for (File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 1){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("pdf")) {
System.out.println("PDF TROVATO: " + f.getName());
// input
String input = win_str(src + f.getName());
// output
String output = target;
output += f.getName().replaceAll(".pdf", ".txt");
output = win_str(output);
// command
String command = "cmd /C java -jar ./pdfbox-app-2.0.11.jar ExtractText ";
command += input + " " + output;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
}
}
// set status, awake other threads
launcher.status = 2;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
SearcherThread.java:
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
public class SearcherThread extends Thread {
// campi
String src = "";
String target = "";
String item = "";
Launcher launcher;
// costruttore
public SearcherThread(Launcher launcher, String src, String target, String item) {
this.target = target;
this.src = src;
this.item = item;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.target);
for(File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 2){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("txt")) {
System.out.println("SEARCHING IN: " + f.getName());
// init
String line;
BufferedReader br = new BufferedReader(new FileReader(new File(target+f.getName())));
// txt search
while((line = br.readLine()) != null) {
if(line.contains(item)) {
System.out.println(" [" + item + "]" + " trovato in " + f.getName() + "\n");
// input
String pdf = f.getName().replaceAll(".txt", ".pdf");
String input = win_str(src+pdf);
// output
String output = win_str(target);
// command
String command = "cmd /C copy " + input + " " + output;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
break;
}
}
}
}
// set status, awake other threads
launcher.status = 3;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}
CleanupThread.java:
import java.io.File;
public class CleanupThread extends Thread {
// campi
String target = "";
Launcher launcher;
// costruttore
public CleanupThread(Launcher launcher, String target) {
this.target = target;
this.launcher = launcher;
}
// metodi
#Override
public void run() {
try{
synchronized (launcher) {
File folder = new File(this.target);
for (File f : folder.listFiles()) {
// spin-lock
while (launcher.status != 3){
launcher.wait();
}
if(f.isFile() && f.getName().endsWith("txt")) {
System.out.println("CLEANING UP: " + f.getName());
// input
String input = win_str(target + f.getName());
// command
String command = "cmd /C del " + input;
Process p1 = Runtime.getRuntime().exec(command);
p1.waitFor();
}
}
// set status, awake other threads
launcher.status = 1;
launcher.notifyAll();
}
}catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
}
}
private String win_str(String str) {
return "\"" + str + "\"";
}
}

Processing huge File quickly in Java

I have a huge CSV file ~800 K records and using that data I have to form a POST request and make a rest call.
Initially I tried WITHOUT using threads but it is taking very long time to process it.
So I thought of using threads to speed up the process and followed below approach.
divided file into relatively smaller files (Tried with 3 files with approx ~5K data each file). (I Did this Manually Before passing to application)
Created 3 threads (traditional way by extending Thread class)
Reads each file with each thread and form HashMap with details required to form request and added it to ArrayList of POST Request
Send Post request to in loop
List item
Get the Response and add it to Response List
Both above approach takes too long to even complete half (>3 hrs). Might be one of them would not be good approach.
Could anyone please provide suggestion which helps me speeding up the process ? It is NOT mandatory to use threading.
Just to add that my code is at the consumer end and does not have much control on producer end.
MultiThreadedFileRead (Main class that Extends Thread)
class MultiThreadedFileRead extends Thread
{
public static final String EMPTY = "";
public static Logger logger = Logger.getLogger(MultiThreadedFileRead.class);
BufferedReader bReader = null;
String filename = null;
int Request_Num = 0;
HashMap<Integer, String> filteredSrcDataMap = null;
List<BrandRQ> brandRQList = null;
List<BrandRS> brandRSList = null;
ReadDLShipFile readDLShipFile = new ReadDLShipFile();
GenerateAndProcessPostBrandAPI generateAndProcessPostBrandAPI = new GenerateAndProcessPostBrandAPI();
MultiThreadedFileRead()
{
}
MultiThreadedFileRead(String fname) throws Exception
{
filename = fname;
Request_Num = 0;
List<BrandRQ> brandRQList = new ArrayList<BrandRQ>();
List<BrandRS> brandRSList = new ArrayList<BrandRS>();
this.start();
}
public void run()
{
logger.debug("File *** : " + this.filename);
//Generate Source Data Map
HashMap<Integer, String> filteredSrcDataMap = (HashMap<Integer, String>) readDLShipFile.readSourceFileData(this.filename);
generateAndProcessPostBrandAPI.generateAndProcessPostRequest(filteredSrcDataMap, this);
}
public static void main(String args[]) throws Exception
{
String environment = ""; // TO BE UNCOMMENTED
String outPutfileName = ""; // TO BE UNCOMMENTED
BrandRetrivalProperties brProps = BrandRetrivalProperties.getInstance();
if(args != null && args.length == 2 && DLPremiumUtil.isNotEmpty(args[0]) && DLPremiumUtil.isNotEmpty(args[1])) // TO BE UNCOMMENTED
{
environment = args[0].trim();
outPutfileName = args[1].trim();
ApplicationInitializer applicationInitializer = new ApplicationInitializer(environment);
applicationInitializer.initializeParams();
logger.debug("Environment : " + environment);
logger.debug("Filename : " + outPutfileName);
// TO BE UNCOMMENTED - START
}else{
System.out.println("Invalid parameters passed. Expected paramenters: Environment");
System.out.println("Sample Request: java -jar BrandRetrival.jar [prd|int] brand.dat");
System.exit(1);
}
MultiThreadedFileRead multiThreadedFileRead = new MultiThreadedFileRead();
List<String> listOfFileNames = multiThreadedFileRead.getFileNames(brProps);
logger.debug("List : " + listOfFileNames);
int totalFileSize = listOfFileNames.size();
logger.debug("totalFileSize : " + totalFileSize);
MultiThreadedFileRead fr[]=new MultiThreadedFileRead[totalFileSize];
logger.debug("Size of Array : " + fr.length);
for(int i = 0; i < totalFileSize; i++)
{
logger.debug("\nFile Getting Added to Array : " + brProps.getCountFilePath()+listOfFileNames.get(i));
fr[i]=new MultiThreadedFileRead(brProps.getCountFilePath()+listOfFileNames.get(i));
}
}
public List<String> getFileNames(BrandRetrivalProperties brProps)
{
MultiThreadedFileRead multiThreadedFileRead1 = new MultiThreadedFileRead();
BufferedReader br = null;
String line = "";
String filename = multiThreadedFileRead1.getCounterFileName(brProps.getCountFilePath(), brProps.getCountFilePathStartsWith());
List<String> fileNameList = null;
logger.debug("filename : " + filename);
if(filename != null)
{
fileNameList = new ArrayList<String>();
try{
br = new BufferedReader(new FileReader(brProps.getCountFilePath()+filename));
while ((line = br.readLine()) != null)
{
fileNameList.add(line);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block ;
e2.printStackTrace();
} catch (Exception e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
} finally
{
if (br != null)
{
try
{
br.close();
} catch (IOException e4)
{
e4.printStackTrace();
} catch (Exception e5)
{
e5.printStackTrace();
}
}
}
}
return fileNameList;
}
// Get the Name of the file which has name of individual CSV files to read to form the request
public String getCounterFileName(String sourceFilePath, String sourceFileNameStartsWith)
{
String fileName = null;
if(sourceFilePath != null && !sourceFilePath.equals(EMPTY) &&
sourceFileNameStartsWith != null && !sourceFileNameStartsWith.equals(EMPTY))
{
File filePath = new File(sourceFilePath);
File[] listOfFiles = filePath.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile() && listOfFiles[i].getName().startsWith(sourceFileNameStartsWith)) {
fileName = listOfFiles[i].getName();
} else if (listOfFiles[i].isDirectory()) {
fileName = null;
}
}
}
return fileName;
}
}
GenerateAndProcessPostBrandAPI
public class GenerateAndProcessPostBrandAPI {
public static Logger logger = Logger.getLogger(GenerateAndProcessPostBrandAPI.class);
List<BrandRQ> brandRQList = new ArrayList<BrandRQ>();
List<BrandRS> brandRSList = new ArrayList<BrandRS>();
DLPremiumClientPost dlPremiumclientPost = new DLPremiumClientPost();
JSONRequestGenerator jsonRequestGenerator = new JSONRequestGenerator();
public List<BrandRQ> getBrandRequstList(Map<Integer, String> filteredSrcDataMap)
{
if(filteredSrcDataMap != null)
{
brandRQList = jsonRequestGenerator.getBrandRQList(filteredSrcDataMap, brandRQList);
}
return brandRQList;
}
public void generateAndProcessPostRequest(Map<Integer, String> filteredSrcDataMap, MultiThreadedFileRead multiThreadedFileRead)
{
if(filteredSrcDataMap != null)
{
brandRQList = jsonRequestGenerator.getBrandRQList(filteredSrcDataMap, brandRQList);
if(brandRQList != null && brandRQList.size() > 0)
{
BrandRetrivalProperties brProps = BrandRetrivalProperties.getInstance();
String postBrandsEndpoint = brProps.getPostBrandsEndPoint();
for (BrandRQ brandRQ : brandRQList)
{
multiThreadedFileRead.Request_Num = multiThreadedFileRead.Request_Num + 1;
logger.debug("Brand Request - " + multiThreadedFileRead.Request_Num + " : " + ObjectToJSONCovertor.converToJSON(brandRQ));
BrandRS brandResponse = dlPremiumclientPost.loadBrandApiResponseJSON(brandRQ, postBrandsEndpoint, DLPremiumUtil.getTransactionID(), BrandConstants.AUTH_TOKEN);
logger.debug("Response - " + multiThreadedFileRead.Request_Num + " : " + ObjectToJSONCovertor.converToJSON(brandResponse));
brandRSList.add(brandResponse);
}
}
}
}
}

encode special character java

I'm trying to fix a bug in the code I wrote which convert a srt file to dxfp.xml. it works fine but when there is a special character such as an ampersand it throws an java.lang.NumberFormatException error. I tried to use the StringEscapeUtils function from apache commons to solve it. Can someone explain to me what it is I am missing here? thanks in advance!
public class SRT_TO_DFXP_Converter {
File input_file;
File output_file;
ArrayList<CaptionLine> node_list;
public SRT_TO_DFXP_Converter(File input_file, File output_file) {
this.input_file = input_file;
this.output_file = output_file;
this.node_list = new ArrayList<CaptionLine>();
}
class CaptionLine {
int line_num;
String begin_time;
String end_time;
ArrayList<String> content;
public CaptionLine(int line_num, String begin_time, String end_time,
ArrayList<String> content) {
this.line_num = line_num;
this.end_time = end_time;
this.begin_time = begin_time;
this.content = content;
}
public String toString() {
return (line_num + ": " + begin_time + " --> " + end_time + "\n" + content);
}
}
private void readSRT() {
BufferedReader bis = null;
FileReader fis = null;
String line = null;
CaptionLine node;
Integer line_num;
String[] time_split;
String begin_time;
String end_time;
try {
fis = new FileReader(input_file);
bis = new BufferedReader(fis);
do {
line = bis.readLine();
line_num = Integer.valueOf(line);
line = bis.readLine();
time_split = line.split(" --> ");
begin_time = time_split[0];
begin_time = begin_time.replace(',', '.');
end_time = time_split[1];
end_time.replace(',', '.');
ArrayList<String> content = new ArrayList<String>();
while (((line = bis.readLine()) != null)
&& (!(line.trim().equals("")))) {
content.add(StringEscapeUtils.escapeJava(line));
//if (StringUtils.isEmpty(line)) break;
}
node = new CaptionLine(line_num, begin_time, end_time, content);
node_list.add(node);
} while (line != null);
} catch (Exception e) {
System.out.println(e);
}
finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String convertToXML() {
StringBuffer dfxp = new StringBuffer();
dfxp.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tt xml:lang=\"en\" xmlns=\"http://www.w3.org/2006/04/ttaf1\" xmlns:tts=\"http://www.w3.org/2006/04/ttaf1#styling\">\n\t<head>\n\t\t<styling>\n\t\t\t<style id=\"1\" tts:backgroundColor=\"black\" tts:fontFamily=\"Arial\" tts:fontSize=\"14\" tts:color=\"white\" tts:textAlign=\"center\" tts:fontStyle=\"Plain\" />\n\t\t</styling>\n\t</head>\n\t<body>\n\t<div xml:lang=\"en\" style=\"default\">\n\t\t<div xml:lang=\"en\">\n");
for (int i = 0; i < node_list.size(); i++) {
dfxp.append("\t\t\t<p begin=\"" + node_list.get(i).begin_time + "\" ")
.append("end=\"" + node_list.get(i).end_time
+ "\" style=\"1\">");
for (int k = 0; k < node_list.get(i).content.size(); k++) {
dfxp.append("" + node_list.get(i).content.get(k));
}
dfxp.append("</p>\n");
}
dfxp.append("\t\t</div>\n\t</body>\n</tt>\n");
return dfxp.toString();
}
private void writeXML(String dfxp) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output_file));
out.write(dfxp);
out.close();
} catch (IOException e) {
System.out.println("Error Writing To File:"+ input_file +'\n');
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
if ((args.length < 2) || (args[1].equals("-h"))) {
System.out.println("\n<--- SRT to DFXP Converter Usage --->");
System.out
.println("Conversion: java -jar SRT_TO_DFXP.jar <input_file> <output_file> [-d]");
System.out
.println("Conversion REQUIRES a input file and output file");
System.out.println("[-d] Will Display XML Generated In Console");
System.out.println("Help: java -jar SRT_TO_DFXP.jar -h");
} else if (!(new File(args[0]).exists())) {
System.out.println("Error: Input SubScript File Does Not Exist\n");
} else {
SRT_TO_DFXP_Converter converter = new SRT_TO_DFXP_Converter(
new File(args[0]), new File(args[1]));
converter.readSRT();
String dfxp = converter.convertToXML();
if ((args.length == 3) && (args[2].equals("-d")))
System.out.println("\n" + dfxp + "\n");
converter.writeXML(dfxp);
System.out.println("Conversion Complete");
}
}
here's part of the srt file that it is throwing an error when exported and run as a jar file.
1
00:20:43,133 --> 00:20:50,599
literature and paper by Liversmith & Newman, and I think the point is well made that a host of factors

Java FTP using Apache commons throws "IOException caught while copying"

I have made a JavaFX application which includes uploading large files (> 1GB) to a server. Every time I got the same error on same place. Any Suggestions what am I doing wrong here.
ftpclient.connect(server, port);
ftpclient.login(ftpuser, ftppass);
ftpclient.enterLocalPassiveMode();
ftpclient.setKeepAlive(true);
ftpclient.setControlKeepAliveTimeout(3000);
Task<Void> copyMnt = new Task<Void>() {
#Override
protected Void call(){
try {
new Thread(new FTPHandler(ftpclient, source , dest)).run();
} catch (IOException ex) {
Logger.getLogger(MyAppController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
};
new Thread(copyMnt).start();
Now on the FTPHandler Class
// The constructor will set the ftpclient, source and destinations.
#Override
public void run() {
try {
uploadDirectory(this.getClient(), this.getDest(), this.getSrc(), "");
} catch (IOException ex) {
Logger.getLogger(FTPHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void uploadDirectory(FTPClient ftpClient,
String remoteDirPath, String localParentDir, String remoteParentDir)
throws IOException {
File localDir = new File(localParentDir);
File[] subFiles = localDir.listFiles();
if (subFiles != null && subFiles.length > 0) {
for (File item : subFiles) {
String remoteFilePath = remoteDirPath + "/" + remoteParentDir
+ "/" + item.getName();
if (remoteParentDir.equals("")) {
remoteFilePath = remoteDirPath + "/" + item.getName();
}
if (item.isFile()) {
// upload the file
String localFilePath = item.getAbsolutePath();
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()) + " : Uploading :: " + localFilePath + " to " + remoteFilePath);
boolean uploaded = uploadSingleFile(ftpClient,
localFilePath, remoteFilePath);
if (uploaded) {
System.out.println("Success : "
+ remoteFilePath);
} else {
System.out.println("Failed : "
+ localFilePath);
}
} else {
// create directory on the server
boolean created = ftpClient.makeDirectory(remoteFilePath);
if (created) {
System.out.println("CREATED the directory: "
+ remoteFilePath);
} else {
System.out.println("COULD NOT create the directory: "
+ remoteFilePath);
}
// upload the sub directory
String parent = remoteParentDir + "/" + item.getName();
if (remoteParentDir.equals("")) {
parent = item.getName();
}
localParentDir = item.getAbsolutePath();
uploadDirectory(ftpClient, remoteDirPath, localParentDir,
parent);
}
}
}
}
Every time I am uploading the files (files are of different types like .iso, .dat etc), The first few files (upload sequence is like first few hundred files are smaller i.e less than few MBs then Last 10 files are more than 1 GB big)will be successfully uploaded (i.e all smaller files and 2 of the last 10 files) but when it starts uploading the third big file I get following exception.
SEVERE: null
org.apache.commons.net.io.CopyStreamException: IOException caught while copying.
at org.apache.commons.net.io.Util.copyStream(Util.java:134)
at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:653)
at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:624)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1976)
The CopyStreamException has a "cause" exception. Check that using the .getCause(), to see what went wrong.
See the Util.copyStream method:
public static final long copyStream(InputStream source, OutputStream dest,
int bufferSize, long streamSize,
CopyStreamListener listener,
boolean flush)
throws CopyStreamException
{
int bytes;
long total = 0;
byte[] buffer = new byte[bufferSize >= 0 ? bufferSize : DEFAULT_COPY_BUFFER_SIZE];
try
{
while ((bytes = source.read(buffer)) != -1)
{
....
}
}
catch (IOException e)
{
throw new CopyStreamException("IOException caught while copying.",
total, e);
}
return total;
}
Somewhere in your uploadSingleFile function, do
try
{
ftpClient.storeFile(...)
}
catch (Exception e)
{
e.printStackTrace();
if (e.getCause() != null)
{
e.getCause().printStackTrace();
}
}
I do not know Java, so the code may not be 100% correct.
See also Getting full string stack trace including inner exception.

inStream.read in serial communications

I'm trying to monitor temperature from a remote device using a TC65 modem. To request, 'C' has to be sent with a carriage return at the end. The problem is, I only get this on my phone: "This is test sms. The current temperature is " without the temperature I requested. I tried communicating with the thermostat using HyperTeminal without a problem.
Could you help me with instream.read? The output is double (accurate by two decimals).
Here's my code. Thanks.
package example.rs232demo;
import javax.microedition.midlet.*;
import java.io.*;
import javax.microedition.io.*;
import com.siemens.icm.io.*;
public class RS232Demo extends MIDlet {
CommConnection commConn;
InputStream inStream;
OutputStream outStream;
private ATCommand ATC;
public static String phone = "+97455781868";
public static String message = "This is test sms.";
/**
* RS232Demo - default constructor
*/
public RS232Demo() {
//System.out.println("RS232Demo: Constructor");
//System.out.println("Available COM-Ports: " + System.getProperty("microedition.commports"));
try {
//String strCOM = "comm:com0;blocking=on;baudrate=115200";
String strCOM = "comm:com0;blocking=on;baudrate=9600;bitsperchar=7;parity=even";
commConn = (CommConnection)Connector.open(strCOM);
//System.out.println("CommConnection(" + strCOM + ") opened");
//System.out.println("Real baud rate: " + commConn.getBaudRate());
inStream = commConn.openInputStream();
outStream = commConn.openOutputStream();
//System.out.println("InputStream and OutputStream opened");
} catch(IOException e) {
//System.out.println(e);
notifyDestroyed();
}
}
/**
* startApp()
*/
public void startApp() throws MIDletStateChangeException {
int ch = 0;
//System.out.println("RS232Demo: startApp");
//System.out.println("Looping back received data, leave with 'Q'...");
try {
outStream.write('C');
outStream.write('\r');
ch = inStream.read();
} catch(IOException e) {
//System.out.println(e);
}
try
{
this.ATC = new ATCommand(false);
}
catch (ATCommandFailedException ex)
{
ex.printStackTrace();
}
send_Simple_SMS(phone, message, ch);
try
{
this.ATC.release();
}
catch(ATCommandFailedException ex)
{
ex.printStackTrace();
}
destroyApp(true);
}
public void pauseApp() {
//System.out.println("RS232Demo: pauseApp()");
}
public int send_Simple_SMS(String phone, String message, int ch)
{
int res = -1;
String AT = "";
String response = "";
synchronized (System.out)
{
}
if(ATC==null){return res;}
try
{
synchronized (ATC)
{
ATC.send("AT+CMGF=1\r");
ATC.send("AT+IFC=1,1\r");
response = "";
response = ATC.send("AT+CMGS=?\r");
if (response.trim().indexOf("OK") < 0)
{
return res;
}
response = ATC.send("AT+CMGS=" + phone + '\r' + '\n');
//System.out.println("Sending.");
response = ATC.send(message + "The current temperature is " + (char)ch + '\032');
//System.out.println("Sent.");
if (response.trim().indexOf("OK") >= 0)
{
res = 0;
}
ATC.notifyAll();
}
}
catch (ATCommandFailedException ex)
{
ex.printStackTrace();
res = -1;
}
return res;
}
public void destroyApp(boolean cond) {
//System.out.println("RS232Demo: destroyApp(" + cond + ")");
try {
inStream.close();
outStream.close();
commConn.close();
//System.out.println("Streams and connection closed");
} catch(IOException e) {
//System.out.println(e);
}
notifyDestroyed();
}
}
Problem is here:
response = ATC.send(message + "The current temperature is " + (char)ch + '\032');
It converts ch to corrensponding character, not to number string.
Try the following:
response = ATC.send(message + "The current temperature is " + ch + '\032');

Categories