FAQ Database Discussion Community


Java audio plays fine when run alone, not when run through separate class

java,audio,java-io
So this class plays the sound file 'Theme A.wav' just fine when ran by itself. This is 'PlayAudio.class' import java.io.*; import sun.audio.*; public class PlayAudio { public static playsound() { String sound = "Theme A.wav"; InputStream audio = new FileInputStream(new File(sound)); AudioStream aStream = new AudioStream(audio); AudioPlayer.player.start(aStream); System.out.println("Loaded playaudio.class; playing...

Java - reading .txt file to arrayList omits last iteration and shows error

java,for-loop,arraylist,java-io
I have a .txt file and require its contents to be put into an arraylist. It is in the following format, Each element(int,String) being on a new line within the document. int number of parts string partname string description int price string partname string description int price etc. Whenever i...

Writing bytes to file then reading yields different bytes

java,file,io,java-io
I have a program that needs to read and write RGB values from a file. However, I encountered an issue with the application where the data I am reading back from a file differs from what I was writing to it. Program: public static void main(String[] args) throws Exception {...

Java IO Server Client read and process users input

java,client-server,java-io
I have a simple Fileserver and Client (code from the web) that let me send files to my other laptop inside my home LAN. Now, the file sent from the server to the client is hardcoded but i want to prompt user at client-side to input a filename, send it...

Line when reading a file is empty but the line is not null

java,bufferedreader,java-io
I have a problem in java and i dont understand why, since i think i am doing text-book stuff. An overview in what of want to do is: I want to create a file that contains in each line two strings: documentPath, documentID (in this format: "documentPath;documentID;") I want to...

Non-Blocking I/O [duplicate]

java,java-io
This question already has an answer here: Blocking in terms of java.io/java.nio 3 answers Non-Blocking I/O generally means that when a thread reads data, it will get as much data as is available and then return immediately. However, I can't seem to get my head around the issue of...

Should BufferedReaders be passed a dynamic FileReader?

java,performance,bufferedreader,filereader,java-io
As the question states, is passing a dynamic FileReader bad practice? Should this/can this FileReader be closed sufficiently? BufferedReader buffReader = new BufferedReader( new FileReader(new File("C:/Path/To/File.txt"))); .... do something buffReader.close(); Should the FileReader also be closed? Would separation be required to do so? Perhaps a simple question, but I'm not...

How to change a value of a file using Java IO function

java,android,java-io
Can anyone help me how to change a line in a file using java IO function. The file is located at SDCard. I have tried some solution from different blog, but failed. I need to change one attribute wpa_oper_channel=1 to 2,3,4..... as user demand in the file sdcard/sample.txt. I have...

Getting IOException while using camel exec component to invoke a batch file

java,apache-camel,java-io
I am using a basic implementation of camel's exec component to invoke a batch file in a windows environment. Whenever the batch file execution fails and it returns non zero exit code along with some error message, my routes work just fine. But whenever the execution is successful, it throw...

Assigning instances of objects to an array

java,arrays,bufferedreader,java-io
I am using bufferedFileReader and lineScanner to read through a csv file, delimiting at commas and assigning the first token in the line to an object of class Team. Each token after this is assigned to a variable of Team. I have this part working fine. The next part is...

Client Server File Transfer

java,java-io
Hi I am having a problem while transferring my files from client to server side. From my initial research, I found DataInputStream which can be used for my transfer. But unfortunately, the files which are transfered using DataInput/Output Stream gets corrupted. The file size remains the same but when i...

JavaIO Input variable value issues

java,java-io
public static void main(String[]someVariableName) throws IOException{ int Actinium = 89; int Ac = Actinium; String element //tried multiple variable data types Scanner in = new Scanner(System.in); System.out.println("Please enter an element"); element = in.next(); System.out.println(element); I'm trying to make a program that when a user inputs an elemt's name or...

Writing byte array to an UTF8-encoded file

java,utf-8,java-io
Given a byte array in UTF-8 encoding (as result of base64 decoding of a String) - what is please a correct way to write it to a file in UTF-8 encoding? Is the following source code (writing the array byte by byte) correct? OutputStreamWriter osw = new OutputStreamWriter( new FileOutputStream(tmpFile),...

How to go down lines when trying to write to a file with Java [duplicate]

java,file,java-io
This question already has an answer here: File Writer overrides previous write Java 2 answers Using the code below, I am trying to make a log for a plugin, though, every time it makes a entry I want it to go below the other entry. Though, when I test...

Copy file with a lock on it

java,file-io,java-io
I have an application running on a server which is doing stuff and writing everything it does to a log file. I also have secondary application which is kind of like a monitoring panel also running on the server but is a different process. What I would like to do...

How to detect directory inside JarFile

java,jar,io,java-io
I am reading jar file using JarFile class and iterating through entities. How can I determine if current entity is a directory? Or maybe someone can provide code to display jar file content in JTree.

Best way to write huge number of files

java,nio,java-io
I am writing a lots of files like bellow. public void call(Iterator<Tuple2<Text, BytesWritable>> arg0) throws Exception { // TODO Auto-generated method stub while (arg0.hasNext()) { Tuple2<Text, BytesWritable> tuple2 = arg0.next(); System.out.println(tuple2._1().toString()); PrintWriter writer = new PrintWriter("/home/suv/junk/sparkOutPut/"+tuple2._1().toString(), "UTF-8"); writer.println(new String(tuple2._2().getBytes())); writer.close(); } } Is there any better way to write the...

Reading file from PATH of URI

java,io,java-io
I have to read a file which can be local or in remote. The file path or URI will come form user input. Currently I am reading only local file,this way public String readFile(String fileName) { File file=new File(fileName); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(file));...

What would I get using Java File.delete() with UNC path if the server response time out

java,java-io,samba,smb,java.nio.file
I have a rather theoritical question for you. What would happen if one calls java.io.File#delete() using a UNC path i.e. new File("\192.168.10.10\MyShare\myFile.txt").delete() and the underlying SMB_COM_DELETE request reaches the SMB server but the SMB_COM_DELETE_RESPONSE does not reach the caller back for some reason (network failure, firewall or whatever)? I would...

HttpClient/BufferedReader returns garbled mess

java,java-io
I have a method to get the source text of a file from a url and return it as a string. but it returns garbled rubbish instead of anything useful. I use the same code in one place in my project and it works perfectly fine, but using it elsewhere...

Serialisation of an Object Java

java,serialization,deserialization,java-io
I would like to serialise/deserialise an object. Code runs but the result in the txt is crap. Here is the code : public class Test implements Serializable { public String[] nom; public Test() { nom = new String[5]; nom[0] = "Coucou"; nom[1] = "Je suis un tab de String"; nom[2]...

ImageIO.read() failing with no exception and a vaild url

java,java-io
I'm have the following code which I seem to be experiencing random image reading failure with with no exceptions. I'm running the following image url in a batch job, some of the other urls work some don't. The failure is ImageIO.read is null although it's a perfectly good working url....

List files in a folder to a JOptionPane

java,nullpointerexception,java-io
Lately I have been working on a program to list the files in a folder so they show up on a JOptionPane. I have tried to get a File[] by calling File.listFiles on the folder object, but it results a NullPointerException on line for (int i = 0; i <...

Blocking in terms of java.io/java.nio

java,java-io
I just read ... Classes that work with streams are located in two packages: java.io and java.nio. Classes from the former implement blocking of input/output (I/O): When bytes are being read/written by a process, they become unavailable for other threads of execution. The latter package offers non-blocking I/O with improved...

How to list only N files in directory using java

java,java-io
If I have a directory contains a lot of files (about 1000 file). Some of these files named .processed and other not. How can I list only 1o unprocessed files. I am using this code to filter the processed file. File[] inputFileList = inputDirectory.listFiles(new FileFilter() { @Override public boolean accept(File...

Timeout-based BufferedWriter flush

java,java-io,bufferedwriter
I'm using BufferedWriter with the default size of 8192 characters to write lines to a local file. The lines are read from socket inputstream using BufferedReader readLine method, blocking I/O. Average line length is 50 characters. It all works well and fast enough (over 1 mln lines per second) however...

How to Count numbers of line, word and characters from Edittext field in Android [closed]

android,java-io
I am beginner, I want to make one simple application that will count number of lines, words and characters from whatever we have entered in Editext field. i want result like: EditText : My name is abc. Button CLick----> Result: No. of Words : 4 No. of Characters : 14...

Displaying directory listings using regular expressions

java,regex,java-io
Here's a code snippet from 'Thinking in Java': import java.io.*; import java.util.*; import java.util.regex.*; public class DirList { public static void main(String[] args){ File path = new File("."); String[] list; if(args.length == 0){ list = path.list(); } else{ //System.out.println(args[0]); list = path.list(new DirFilter(args[0])); } Arrays.sort(list, new AlphabeticComparator()); System.out.println(list.length); for(int i...

java repeat one part of the output

java,eclipse,io,filereader,java-io
I have Java assignment , and this is the explanation of the In your program create three classes: InputHandler, OutputHandler and Student classes. The InputHandler class handles the reading of information from the input file. It also contains an array of Student objects to store the information in it. The...

how to read File from a particular line till the end of the File in java

java,java-io
I have this File : Line1. Line2. Line3. Line4. I want to start reading from the second line (Line2) till the end of the file. How can i do this in Java? ...

Java multiple objects reading different parts of same file [closed]

java,java-io
I am working on a project where I will have a binary file. The file is split into multiple sections, each of which represents a list of primitive values. I need a solution where I can have a collection of objects, each of which represents a section of the file....

How to prevent the file to overwrite itself?

java,java-io
i've edited the code, can you please tell me how i can write each line at the end of the file? Here it's been written on the same line. Can you help please? private void okMouseClicked(java.awt.event.MouseEvent evt) { String pass = name.getText(); if (pass.equals("")){ error.setText("Name of Entity should not be...

after socket.accept() statement no other statement is executing how to make accept by server?

java,sockets,java-io
the code snippet i'm trying to execute ServerSocket ss=new ServerSocket(7777); Socket socket=ss.accept(); System.out.println("Connection:"+socket.isConnected()); i'm trying to get data from another program to this class i'm using same port for Socket,ServerSocket. another program code Socket socket=new Socket("localhost",7777); fileData.append(LineNumber + ": " + inputLine + "\n");//fileData is jtext area DataOutputStream dos4=new DataOutputStream(socket.getOutputStream());...

ServerSocket while not breaks on image data inputstream

java,android,io,java-io
I tried to send an image from One device to other Device using Bluetooth.For that I take Android Bluetooth chat application source code and it works fine when I send String.But If i send image as byte array the while loop not breaks or EOF not reached when read from...

InputStream vs Reader [duplicate]

java,java-io
This question already has an answer here: java reader vs. stream 1 answer I am going over input output section and there are so much classes and interfaces that I am confused a little bit. As documentation says InputStream is a byte based stream whereas Reader is character-based stream....

Why is InputStream.close() declared to throw IOException while reading the message?

java,inputstream,java-io,ioexception,close
Recently, I started doing automation, which suggests that I am not properly closing streams. I decide to see if there's anything that can be done with a finally{} block, and then I see, close() can throw IOException. public Iterable<T> convertToMessage(Class<T> messageClazz, MESSAGE_FORMAT messageFormat, File fileToConvert, String duns) throws IOException {...