[英]Java File I/O problems
這是我第一次使用java中的文件i / o,但它不起作用。 我解析單個行並輸出分號分隔行的程序部分在我硬編碼文件並在屏幕上顯示時就像一個魅力。
當我嘗試寫一個文件時, public static OutputStream...
錯誤地作為一個illegal start to expression
,我一直無法讓程序逐步遍歷整個文件目錄而不是一個。
我不清楚的地方:我注意在任何地方設置輸出文件名...我應該這樣做嗎? 路徑變量不會通過。 路徑的正確格式是什么? 任何人都可以看到我需要調試的內容嗎?
import java.nio.*;
public class FileReadSSCCE
{
public static void main(String args[])
{
try
{
Path startingDir = Paths.get("R:\Data\cs\RoboHelp\CorrLib\Output\Production\WebHelp");
PrintFiles pf = new PrintFiles();
Files.walkFileTree(startingDir, pf);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String inputLine;
String desc = "";
String docNo = "";
//Read File Line By Line
while ((inputLine = br.readLine()) != null)
{
int testVal=0;
int stringMax = inputLine.length();
//
if(inputLine.startsWith("Description"))
{desc = inputLine.substring(13,inputLine.length());}
else
if(inputLine.startsWith("Reference Number"))
{docNo = inputLine.substring(20,inputLine.length());}
}
// Print the content on the console
String outStr1 = (desc + ";" + docNo);
System.out.print(inputLine + "\n" + outStr1);
String lineItem = (outStr1);
//
try (OutputStream out = new BufferedOutputStream
(logfile.newOutputStream(CREATE, APPEND)))
{
out.write(lineItem, 0, lineItem.length);
}
catch (IOException x)
{
System.err.println(x);
}
public static OutputStream newOutputStream() throws IOException
{
// append to an existing file, create file if it doesn't initially exist
out = Files.newOutputStream((Paths.get("c:\javaout.txt"), CREATE, APPEND);
}
//Close the input stream
in.close();
}
catch (Exception e)
{
//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
在Files.newOutputStream(c:, CREATE, APPEND);
你有一個語法錯誤,因為c:
部分。 您必須將Path
實例傳遞給Files.newOutputStream()
。
您可以使用Paths
某個方法獲取此類實例。
同樣,你似乎想要初始化類似這樣的startingPath
(使用字符串):
Path startingPath = "R:\Data\cs\RoboHelp\CorrLib\Output\Production\WebHelp";
但是您需要使用Paths
將String
轉換為Path
:
Path startingPath = Paths.get("R:\Data\cs\RoboHelp\CorrLib\Output\Production\WebHelp");
你的意思是:
Path startingDir = Paths.get("R:/Data/cs/RoboHelp/CorrLib/Output/Production/WebHelp");
?
同樣在您的代碼中,fstream未初始化。 您是否在訪問者的visitFile
方法中復制了代碼邏輯?
然后在main方法中定義一個方法 - 這是不允許的:
public static OutputStream newOutputStream() throws IOException
{
// append to an existing file, create file if it doesn't initially exist
out = Files.newOutputStream(c:, CREATE, APPEND);
}
路徑必須是雙引號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.