在 DB2 for Linux, UNIX and Windows 中使用管道加载数据
2010-04-27 00:00:00 来源:WEB开发网使用 UNIX 管道的示例 Java 程序
在 UNIX 中,您不需要通过 Java 代码来调用 C 程序和创建指定管道。这是因为 UNIX 可以直接使用 mkfifo 或 mknod 命令来创建指定管道。清单 4 中的代码展示了在 UNIX 中使用指定管道的示例。
清单 4. 使用指定 UNIX 管道的示例 TestUnixPipe.java 程序
package ibm;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class TestUnixPipe
{
FileChannel fc;
int multiTables[] = new int[1];
String filesep = System.getProperty("file.separator");
String fileName, OUTPUT_DIR = ".", pipeName;
int pipeBuffer = 131072, fileBuffer = 8192;
public TestUnixPipe(String fileName, String output)
{
this.fileName = fileName;
this.OUTPUT_DIR = output;
multiTables[0] = 0;
}
private void log(String message)
{
System.out.println(message);
}
public void runPipe()
{
int bytesReturn;
pipeName = OUTPUT_DIR + "data" + filesep + pipeName + ".pipe";
File pipeFile = new File(pipeName);
pipeFile.deleteOnExit();
if (!pipeFile.exists())
{
try
{
Runtime.getRuntime().exec("mkfifo " +
pipeFile.getAbsolutePath());
} catch (Exception e)
{
e.printStackTrace();
}
}
FileOutputStream fos = null;
try
{
if (multiTables[0] == 0)
{
fos = new FileOutputStream(pipeFile);
fc = fos.getChannel();
} else
{
fc = fc;
}
} catch (Exception e)
{
e.printStackTrace();
}
try
{
File f1 = new File(this.fileName);
InputStream in = new FileInputStream(f1);
log("Sending data to the pipe");
byte[] buf = new byte[fileBuffer];
int len;
while ((len = in.read(buf)) > 0)
{
bytesReturn = fc.write(ByteBuffer.wrap(buf));
log("Sent " + len + "/" + bytesReturn +
" bytes to the pipe");
if (bytesReturn == -1)
{
log("Error Writing to pipe " + pipeName);
}
}
in.close();
log("Writing to the pipe completed.");
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException,
InterruptedException
{
String output = ".";
String fileName = "/home/db2inst1/db2tabledata.txt";;
TestUnixPipe testPipe = new TestUnixPipe(fileName, output);
testPipe.runPipe();
}
}
更多精彩
赞助商链接