이 기사는 Java 읽기 및 쓰기 작업에 대한 코드 예제를 제공합니다. 필요한 친구가 참조할 수 있기를 바랍니다.
java code:
Write:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public void getNotice(HttpServletRequest request, String notice){
String message = JSON.toJSONString(notice);
File file = new File(request.getRealPath( "/text/history.txt" ));
try (OutputStreamWriter op = new OutputStreamWriter( new FileOutputStream(file , true), "utf-8" )){
if (!file.exists()){
file.createNewFile();
}
op.append(message);
op.write( "\r\n" );
op. flush ();
op.close();
} catch (IOException e){
e.printStackTrace();
}
}
|
로그인 후 복사
Read:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public void postNotice (HttpServletRequest request, HttpServletResponse response){
JSONObject json = new JSONObject();
String message = "" ;
File file = new File(request.getRealPath( "/text/history.txt" ));
try {
FileInputStream in = new FileInputStream(file);
int len = 0;
byte[] buff = new byte[1024];
while ((len = in.read(buff))!= -1){
message = new String(buff,0 ,len, "utf-8);
}
} catch (IOException e){
}
String str1 = JSONObject.toJSONString(message.replaceAll( "\r|\n" , "" ));
json.put( "str" , str1);
returnMessage(response ,json);
}
|
로그인 후 복사
1 읽을 때 콜백 함수는 console을 인쇄해야 합니다. .log( JSON.parse(데이터 .str));
2. 인코딩 형식 오류가 없는지 확인하려면 저장된 텍스트의 txt를 UTF-8 형식으로 설정하는 것이 좋습니다.
위 내용은 Java 읽기 및 쓰기 작업의 코드 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!