我試圖從線HDFS文件中的行讀取,然後通過線創建一個HDFS文件,並寫入其行。我使用的代碼如下所示:Bufferreader和Bufferwriter用於讀取和寫入文件HDFS
Path FileToRead=new Path(inputPath);
FileSystem hdfs = FileToRead.getFileSystem(new Configuration());
FSDataInputStream fis = hdfs.open(FileToRead);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
line = reader.readLine();
while (line != null){
String[] lineElem = line.split(",");
for(int i=0;i<10;i++){
MyMatrix[i][Integer.valueOf(lineElem[0])-1] = Double.valueOf(lineElem[i+1]);
}
line=reader.readLine();
}
reader.close();
fis.close();
Path FileToWrite = new Path(outputPath+"/V");
FileSystem fs = FileSystem.get(new Configuration());
FSDataOutputStream fileOut = fs.create(FileToWrite);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fileOut));
writer.write("check");
writer.close();
fileOut.close();
當我在outputPath文件中運行此代碼時V尚未創建。但是,如果我將零件替換爲用於寫入的零件,則將創建文件並將檢查寫入其中。 任何人都可以請幫我理解如何正確使用它們,以便能夠先讀取整個文件,然後逐行寫入文件?
我也曾嘗試另一個代碼從一個文件讀取和寫入到另一個,但該文件將被創建,但沒有什麼寫進了!
我用某事像這樣:
hadoop jar main.jar program2.Main input output
然後在我的第一份工作,我從ARG閱讀[0]和寫在args [1] +「/ NewV」的文件中的地圖減少類和它作品。 以我其他類(非地圖減少)我使用ARGS [1] +「/ NewV」作爲輸入路徑和輸出+「/ V_0」作爲輸出路徑(I通過這些字符串的構造函數)。這裏是該類的代碼:
public class Init_V {
String inputPath, outputPath;
public Init_V(String inputPath, String outputPath) throws Exception {
this.inputPath = inputPath;
this.outputPath = outputPath;
try{
FileSystem fs = FileSystem.get(new Configuration());
Path FileToWrite = new Path(outputPath+"/V.txt");
Path FileToRead=new Path(inputPath);
BufferedWriter output = new BufferedWriter
(new OutputStreamWriter(fs.create(FileToWrite,
true)));
BufferedReader reader = new
BufferedReader(new InputStreamReader(fs.open(FileToRead)));
String data;
data = reader.readLine();
while (data != null)
{
output.write(data);
data = reader.readLine();
}
reader.close();
output.close(); }catch(Exception e){
}
}
}
該文件是否存在於本地路徑上?可能是你要用本地上下文('file:/// path/to/file')傳遞輸出路徑,或者默認的文件系統是本地的。你可以分享你啓動程序的調用行,以及$ HADOOP_CONF/core-site中的'fs.default.name'的值。xml' – 2013-05-12 21:13:43
其實我試圖讀取的文件是由HDFS中的另一個作業創建的文件。它位於HDFS中的輸出目錄中。讀完這個文件後,我可以在同一個目錄輸出中(在HDFS中)創建要寫入的文件。我使用「hadoop fs -get output output」將其複製到我的本地機器,當我檢查新創建的文件時,它是空的! – 2013-05-12 21:24:45