Does Java ME allow you to read a line from an InputStream?
This is not as trivial as it sounds. Unfortunately, lines could end with '\r', '\n' or '\r\n'. The following class will handle all of these cases.
public class LineReader{
private Reader in;
private int bucket=-1;
public LineReader(Reader in){
this.in=in;
}
public boolean hasLine() throws IOException{
if(bucket!=-1)return true;
bucket=in.read();
return bucket!=-1;
}
//Read a line, removing any /r and /n. Buffers the string
public String readLine() throws IOException{
int tmp;
StringBuffer out=new StringBuffer();
//Read in data
while(true){
//Check the bucket first. If empty read from the input stream
if(bucket!=-1){
tmp=bucket;
bucket=-1;
}else{
tmp=in.read();
if(tmp==-1)break;
}
//If new line, then discard it. If we get a \r, we need to look ahead so can use bucket
if(tmp=='\r'){
int nextChar=in.read();
if(tmp!='\n')bucket=nextChar;//Ignores \r\n, but not \r\r
break;
}else if(tmp=='\n'){
break;
}else{
//Otherwise just append the character
out.append((char) tmp);
}
}
return out.toString();
}
}
It does eg. by calling read() in loop until newline's found.
Related
I'm using the javascript SDK of Microsoft Speech Synthesizer and calling speakTextAsync to convert text to speech.
This works perfectly, but sometimes the text is long and I want to be able to cancel in the middle, but I cannot find any way to do this. The documentation doesn't seem to indicate any way to cancel. The name speakTextAsync suggests that it returns a Task that could be cancelled, but in fact the method returns undefined, and I can't find any other way to do this. How can this be done?
Seems there is no way to stop it when it is speaking. But actually,as a workaround, you can just download the audio file and play the file yourself so that you can control everything. try the code below:
import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import java.nio.file.*;
import java.io.*;
import javax.sound.sampled.*;
public class TextToSpeech {
public static void main(String[] args) {
try {
String speechSubscriptionKey = "key";
String serviceRegion = "location";
String audioTempPath = "d://test.wav"; //temp file location
SpeechConfig config = SpeechConfig.fromSubscription(speechSubscriptionKey, serviceRegion);
AudioConfig streamConfig = AudioConfig.fromWavFileOutput(audioTempPath);
SpeechSynthesizer synth = new SpeechSynthesizer(config, streamConfig);
String filePath = "....//test2.txt"; // .txt file for test with long text
Path path = Paths.get(filePath);
String text = Files.readString(path);
synth.SpeakText(text);
Thread thread = new Thread(new Speaker(audioTempPath));
thread.start();
System.out.println("play audio for 8s...");
Thread.sleep(8000);
System.out.println("stop play audio");
thread.stop();
} catch (Exception ex) {
System.out.println("Unexpected exception: " + ex);
assert (false);
System.exit(1);
}
}
}
class Speaker implements Runnable {
private String path;
public String getText(String path) {
return this.path;
}
public Speaker(String path) {
this.path = path;
}
public void run() {
try {
File file = new File(path);
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
Clip clip;
stream = AudioSystem.getAudioInputStream(file);
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
I am trying to upload a file to OneDrive special folder using the java sdk but I am getting the following error
Error code: BadRequest Error message: Multiple action overloads were found with the same binding parameter for 'microsoft.graph.createUploadSession'.
Here is a snippet of the java code I am using
private void uploadFile(IGraphServiceClient graphClient, File localFile, String onedriveFileName) throws IOException, InterruptedException {
// Get an input stream for the file
InputStream fileStream = new FileInputStream(localFile);
long streamSize = localFile.length();
// Create a callback used by the upload provider
IProgressCallback<DriveItem> callback = new IProgressCallback<DriveItem>() {
#Override
// Called after each slice of the file is uploaded
public void progress(final long current, final long max) {
LOGGER.trace(String.format("Uploaded %d bytes of %d total bytes", current, max));
}
#Override
public void success(final DriveItem result) {
LOGGER.info(String.format("Uploaded file with ID: %s", result.id));
}
public void failure(final ClientException ex) {
LOGGER.error(String.format("Error uploading file: %s", ex.getMessage()));
}
};
try {
// Create an upload session
UploadSession uploadSession = graphClient
.me()
.drive().special("approot")
.itemWithPath(onedriveFileName)
.createUploadSession(new DriveItemUploadableProperties())
.buildRequest()
.post();
ChunkedUploadProvider<DriveItem> chunkedUploadProvider =
new ChunkedUploadProvider<DriveItem>
(uploadSession, graphClient, fileStream, streamSize, DriveItem.class);
// Config parameter is an array of integers
// customConfig[0] indicates the max slice size
// Max slice size must be a multiple of 320 KiB
int[] customConfig = {320 * 1024};
// Do the upload
chunkedUploadProvider.upload(callback, customConfig);
} catch(IOException ex){
throw ex;
} catch (Exception ex) {
throw ex;
}
}
Any help appreciated.
Thanks
My issue is that I had special characters in the filename, removing them fixed it for me.
My problem is printwriter method. I don't know why it doesn't save text from the console to the text file. It should work but the only line that is saved in the file is "quit". I `m new to Java and this forum. Hopefully, someone will be able to help me.
Greetings
Michal
public class Output3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line= "";
try {
PrintWriter ska = new PrintWriter("trial1");
while(!linia.equals("quit"))
linia = scanner.nextLine();
ska.println(line);
ska.flush();
System.out.println("Message saved");
} catch(IOException e){
e.printStackTrace();
}
}
}
Have you seen that you read from the input stream through the variable linia and write data from the variable line to your file? Have you tried writing using the following line?
ska.println(linia);
So what I'm trying to do is receive the name of a text file that contains a list of filenames of a sequence of images that I have stored in a separate folder. So I get the path to the actual image files using a scanner and scan through each line of the text file, therefore reading the names of the image files in the context of their actual location. Note that the text file and folder of the images have the same path. My question is how do I get these images into my ArrayList of PImages so I can then later load and display them sequentially in a repeating loop using draw()?
private List <PImage> myImage;
private int myFrameRate, myImageNumber;
private Boolean myRunningStatus;
public AnimationPanel(String path, String textFilename) throws FileNotFoundException {
myImage = new ArrayList <PImage>();
Scanner scanner = new Scanner(new File(path + textFilename));
myFrameRate = 20;
myRunningStatus = true;
myImageNumber = 0;
while(scanner.hasNextLine()){
loadImage(path + scanner.nextLine());
myImageNumber++;
}
scanner.close();
}
public void play() {
myRunningStatus = true;
}
public void pause() {
myRunningStatus = false;
}
public void setup() {
size(300, 200);
frameRate(myFrameRate);
}
public void draw() {
background(255);
if(myRunningStatus == true){
image(myImage.get(myImageNumber), 0, 0);
}
}
I think (untested)
while(scanner.hasNextLine()){
PImage p = loadImage(path + scanner.nextLine());
myImage.add(p);
}
I am developing a simple Java IDE like Netbeans/Eclipse. My GUI includes two JTextArea component, one used as a TextEditor where the end user can type in his programs and the other used as an output window.
I am running the users programs by invoking the windows command prompt through Java Runtime and Process classes. I am also catching the IO streams of the process using the methods getInputStream(), getErrorStream(), getOutputStream().
If the program contains only the statements to print something onto the screen, I am able to display the output on the output window(JTextArea). But if it includes statements to read input from the user, then it must be possible for the user to type the expected input value via the output window and it must be sent to the process just as in Netbeans/Eclipse.
I also checked the following link
java: work with stdin/stdout of process in same time
Using this code, I am able to display only the statements waiting for input and not simple output statements. Also, only a single line is displayed on the output window at a time.
It would be great if anybody can help me to resolve this issue.
Thanks
Haleema
I've found the solution with little modification to the earlier post java: work with stdin/stdout of process in same time
class RunFile implements Runnable{
public Thread program = null;
public Process process = null;
private JTextArea console;
private String fn;
public RunFile(JTextArea cons,String filename){
console = cons;
fn=filename;
program = new Thread(this);
program.start();
}
#Override
public void run() {
try {
String commandj[] = new String[4];
commandj[0] = "cmd";
commandj[1]="/C";
commandj[2]="java";
commandj[3] = fn;
String envp[] = new String[1];
envp[0]="path=C:/Program Files (x86)/Java/jdk1.6.0/bin";
File dir = new File("Path to File");
Runtime rt = Runtime.getRuntime();
process = rt.exec(commandj,envp,dir);
ReadStdout read = new ReadStdout(process,console);
WriteStdin write = new WriteStdin(process, console);
int x=process.waitFor();
console.append("\nExit value: " + process.exitValue() + "\n");
}
catch (InterruptedException e) {}
catch (IOException e1) {}
}
}
class WriteStdin implements Runnable{
private Process process = null;
private JTextArea console = null;
public Thread write = null;
private String input = null;
private BufferedWriter writer = null;
public WriteStdin(Process p, JTextArea t){
process = p;
console = t;
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
write = new Thread(this);
write.start();
console.addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyTyped(java.awt.event.KeyEvent e){
//save the last lines for console to variable input
if(e.getKeyChar() == '\n'){
try {
int line = console.getLineCount() -2;
int start = console.getLineStartOffset(line);
int end = console.getLineEndOffset(line);
input = console.getText(start, end - start);
write.resume();
} catch (BadLocationException e1) {}
}
}
});
console.addCaretListener(new javax.swing.event.CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
console.setCaretPosition(console.getDocument().getLength());
throw new UnsupportedOperationException("Not supported yet.");
}
});
console.addFocusListener(new java.awt.event.FocusAdapter() {
#Override
public void focusGained(java.awt.event.FocusEvent e)
{
console.setCaretPosition(console.getDocument().getLength());
}
});
}
#Override
public void run(){
write.suspend();
while(true){
try {
//send variable input in stdin of process
writer.write(input);
writer.flush();
} catch (IOException e) {}
write.suspend();
}
}
}
class ReadStdout implements Runnable{
public Thread read = null;
private BufferedReader reader = null;
private Process process = null;
private JTextArea console = null;
public ReadStdout(Process p,JTextArea t){
process = p;
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
console = t;
read = new Thread(this);
read.start();
}
public void run() {
String line;
try {
while((line = reader.readLine())!=null)
console.append(line+"\n");
}catch (IOException e) {}
}
}