Is there a way to create FileInputStream with mark feature? - java

Is there any possible way to create FileInputStream with mark supported feature as true?

Wrap your Fileinputstream inside a BufferedInputStream.
The buffered streams support marks.

Wrap it in BufferedInputStream.
instead of
FileInputStream fis = new FileInputStream(...);
do this:
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(...));
and use bis instead of fis; nothing else should have to change in your code.

BufferedInputStreams are not magic. They will only support marking for as large as their underlying buffers and these buffers are going to take up memory. So if you go down this route its important that you understand the usage case and potentially call the BufferedInputStream constructor with the appropriatedly sized buffer. If the underlying file starts to get large and you mark far enough back then this technique may not work for you.

Try something like this
public FileInputStream fstream;
public DataInputStream in;
public BufferedInputStream bs;
public String path;
public void myExample() throws IOException{
path = "yourPath";
try {
fstream = new FileInputStream(path);
in = new DataInputStream(fstream);
bs = new BufferedInputStream(new InputStreamReader(in));
//do something
br.close(); //when do something is completed
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "File not found");
}
}

Related

Convert from ByteArrayInputStream to BufferedInputStream in Java InputStream

I have a program where the user chooses a filepath that is getting passed as a string.
Now I have a function that should create a BufferedInputStream taking that string and assigning it to a InputStream.
try (final InputStream is = IOUtils.toInputStream(pathToFile) ) { ...
My problem here is that I am getting a ByteArrayInputStream instead of a "normal" BufferedInputStream. If I print the variable "is".
Is there a way to guarantee that it has to be a BufferedInputStream or can I cast to a BufferedInputStream?
I also tried this:
try (final InputStream is = new ByteArrayInputStream(pathToFile.getBytes(StandardCharsets.UTF_8)) ) {
But this didn't work.
Okay I dont know if that might be a workaround but:
try (final InputStream is = IOUtils.toInputStream(pathToFile) ) {
final InputStream xs = new BufferedInputStream(is);
Works for me. XS is a BufferedInputStream now.
you can get input stream as below
try(InputStream input = new BufferedInputStream(new FileInputStream(pathToFile)))

Java write exe file

is it possible to write/create an exe file in Java?
I can successfully read it but writing the exact same data that has been read to a new file seems to create some trouble because Windows tell's me it's not supported for my pc anymore.
This is the code I'm using to read the file where path is a String given with the actual path (it's in the .jar itself that's why I'm using ResourceAsStream()):
try {
InputStream inputStream = FileIO.class.getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
ArrayList<String> _final = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
_final.add(line);
}
inputStream.close();
return _final.toArray(new String[_final.size()]);
}catch(Exception e) {
return null;
}
This is the code I'm using to write the file:
public static void writeFileArray(String path, String[] data) {
String filename = path;
try{
FileWriter fileWriter = new FileWriter(filename);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(String d : data) {
bufferedWriter.write(d + "\n");
}
bufferedWriter.close();
}
catch(IOException ex){
System.out.println("FileIO failed to write file, IO exception");
}
}
So it doesn't give me any error's or something and the file size of the original .exe and the 'transferred' .exe stays the same, but it doesn't work anymore. Am I just doing it wrong? Did I forget something? Can u even do this with Java?
Btw I'm not that experienced with reading/writing files..
Thanks for considering my request.
I'm going to guess that you're using a Reader when you should be using a raw input stream. Use BufferedInputStream instead of BufferedReader.
BufferedInputStream in = new BufferedInputStream( inputStream );
The problem is that Reader interprets the binary as your local character set instead of the data you want.
Edit: if you need a bigger hint start with this. I just noticed you're using a BufferedWriter too, that won't work either.
try {
InputStream inputStream = FileIO.class.getResourceAsStream(path);
BufferedInputStream in = new BufferedInputStream( inputStream );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[ 1024 ];
for( int length; ( length = ins.read( bytes ) ) != -1; )
bos.write( bytes, 0, length );
}
inputStream.close();
return bos;
When you are using Java 7 or newer, you should copy a resource to a file using
public static void copyResourceToFile(String resourcePath, String filePath) {
try(InputStream inputStream = FileIO.class.getResourceAsStream(resourcePath)) {
Files.copy(inputStream, Paths.get(filePath));
}
catch(IOException ex){
System.out.println("Copying failed. "+ex.getMessage());
}
}
This construct ensures correct closing of the resources even in the exceptional case and the JRE method ensures correct and efficient copying of the data.
It accepts additional options, e.g. to specify that the target file should be overwritten in case it already exists, you would use
public static void copyResourceToFile(String resourcePath, String filePath) {
try(InputStream inputStream = FileIO.class.getResourceAsStream(resourcePath)) {
Files.copy(inputStream, Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
}
catch(IOException ex){
System.out.println("Copying failed. "+ex.getMessage());
}
}
You are using InputStreams for strings, .exe files are bytes!
Try using a ByteArrayInputStream and ByteArrayOutputStream.
Edit: completing with markspace's answer:
new BufferedInputStream(new ByteArrayInputStream( ... ) )

How to prevent the finding "Validation.EncodingRequired" in Java

Recently, I used the AppScan Source to scan the coding, and it found out one of the finding which I don't know how to fix and pass to the scanner or is it a false alarm?
Here's my code.
public static void copyFileUsingFileStreams(File source, File dest)
throws IOException
{
InputStream input = null;
OutputStream output = null;
try
{
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead); //Scanner reported that's a vulnerability in API OutputStream.write()
}
}
finally
{
input.close();
output.close();
}
}
Looks fine to me. There's no need for an encoding if you're writing bytes. If you were writing characters, that would be a different matter.
That said, you really ought to be wrapping your streams in buffered versions:
output = new BufferedOutputStream(new FileOutputStream(dest));
and similarly for input. That doesn't affect anything to do with encodings, but it will make the file I/O more efficient.
You should also change your finally block:
finally
{
if (input!=null)
input.close();
if (output!=null)
output.close();
}
When you start to catch and deal with IOExceptions, as you ought to be doing, you'll be risking a NullPointerException if anything goes wrong while your streams are being created.

How to modify text of a text-file which is read using FileInputStream

I have to use a method whose signature is like this
aMethod(FileInputStream);
I call that method like this
FileInputStream inputStream = new FileInputStream(someTextFile);
aMethod(inputStream);
I want to remove/edit some char which is being read from someTextFile before it being passed into aMethod(inputStream);
I cannot change aMethod's signature or overload it. And, it just take a InputStream.
If method taking a string as param, then I wouldn't be asking this question.
I am InputStream noob. Please advise.
you can convert a string into input stream
String str = "Converted stuff from reading the other inputfile and modifying it";
InputStream is = new ByteArrayInputStream(str.getBytes());
Here is something that might help. It will grab your .txt file. Then it will load it and go through line by line. You have to fill in the commented areas to do what you want.
public void parseFile() {
String inputLine;
String filename = "YOURFILE.txt";
Thread thisThread = Thread.currentThread();
ClassLoader loader = thisThread.getContextClassLoader();
InputStream is = loader.getResourceAsStream(filename);
try {
FileWriter fstream = new FileWriter("path/to/NEWFILE.txt");
BufferedWriter out = new BufferedWriter(fstream);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
while((inputLine = reader.readLine()) != null) {
String[] str = inputLine.split("\t");
if(/* IF WHAT YOU WANT IS IN THE FILE ADD IT */) {
// DO SOMETHING OR ADD WHAT YOU WANT
out.append(str);
out.newLine();
}
}
reader.close();
out.close();
} catch (Exception e) {
e.getMessage();
}
}
Have you looked at another class FilterInputStream which also extends InputStream which may fit into your requirement?
From the documentation for the class
A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.
Also have a look at this question which also seems to be similar to your question.

What is the difference between ObjectInputStreamReader and InputStreamReader?

My teacher said that in file server program ObjectInputStreamReader is compulsory to write. When I asked the reason then he said me it is comfortable for file server program. I am thinking that it is not necessary reason. Why InputStreamReader or other alternatives can not be used? what is the advantage of ObjectInputStreamReader over InputStreamReader.
Here code for client/server:
public class Client {
public static void main(String[] args) {
Socket s = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
Scanner sc = new Scanner(System.in);
String data = "";
try {
s = new Socket("localhost", 1234);
System.out.println("client is connectd");
ois = new ObjectInputStream(s.getInputStream());
String jai = (String) ois.readObject();
System.out.println("DATA from SERVER:" + jai);
oos = new ObjectOutputStream(s.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Enter file name:");
try {
String fil = (String) sc.next();
OutputStream pw = new FileOutputStream(fil + ".new");
oos.writeObject(fil);
data = (String) ois.readObject();
pw.write(data.getBytes());
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Content of file:" + data);
}
}
Can any one say what is actual reason ?
I think you mean ObjectInputStream and BufferedInputStream (not readers).
ObjectInputStream wraps input stream and provides typed methods that allow reading data of certain type from the stream. For example readDouble(), readObject() etc.
BufferedInputStream does not provide additional API (comparing to regular InputStream). The only thing it does is buffering of data, i.e. it reads data chunk-by-chunk that is much more efficient way than reading byte-by-byte.
An InputStream is an abstract class that can be used to define any type of input stream, including reading from file systems, URLs, sockets, etc.
You don't actually create an InputStream, as it doesn't mean anything by itself. Rather, you create a type of InputStream that defines how to read/write a particular type of data, such as the suggested ObjectInputStream. This class defines that the data being written is a Java Object (that implements Serializable or Externalizable). There are other InputStreams that are used for generic file data, images, audio, and a whole range of other types.
There is no such thing as an ObjectInputStreamReader, unless you write a class like this yourself that has the purpose of writing to an ObjectInputStream.
Refer to the ObjectInputStream and InputStream Java docs for more enlightenment

Categories