Buffering FileInputStream with FileChannel?

I

iksrazal

Hi all,

I have a method which via Runtime.exec creates a new, potentially very
large, MySQL DB via its shell client:

public void loadData(String _dbname, String _host, String _dbuser,
String _dbpassword, String _scriptpath) throws MySQLImporterException
{

String[] cmd = new String[]{this.mysql_path,
_dbname,
"--host=" + _host,
"--user=" + _dbuser,
"--password=" + _dbpassword
};
System.err.println(cmd[0] + " " + cmd[1] + " " +
cmd[2] + " " + cmd[3]);

try {

Runtime rt = Runtime.getRuntime();
Process fRuntimeProcess = rt.exec(cmd);
FileInputStream fis = new FileInputStream(_scriptpath);
FileChannel fChan = fis.getChannel();
fChan.transferTo(0, fChan.size(),
Channels.newChannel(fRuntimeProcess.getOutputStream()));

} catch (Exception e) {
e.printStackTrace();
}

} // end loadData()

However reading the article from this site and the code below says by
buffering FileInputStream a performance boost of "100 times faster" was
realized:

http://java.sun.com/docs/books/performance/1st_edition/html/JPIOPerformance.fm.html

public static void copy(String from, String to) throws IOException{
InputStream in = null;
OutputStream out = null;
try {
InputStream inFile = new FileInputStream(from);
in = new BufferedInputStream(inFile);
OutputStream outFile = new FileOutputStream(to);
out = new BufferedOutputStream(outFile);
while (true) {
int data = in.read();
if (data == -1) {
break;
}
out.write(data);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}

My questions are:

(1) Considering my loadData() method uses FileInputStream to get a new
FileChannel, how could I buffer it?

(2) In this context could buffering potentially improve performance?

iksrazal
 
E

Esmond Pitt

Your first version with FileChannel.transferTo() will be faster.

The 100 times improvement with BufferedInput/OutputStreams in your
second example doesn't happen by comparison with your first example, it
happens when reading and writing a byte at a time, which is a stupid
idea anyway.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top