当仅使用一个资源时,Java 7 try-with-resources语法(也称为ARM块(自动资源管理))很好,简短而直接AutoCloseable.但是,当我需要声明彼此依赖的多个资源时,我不确定什么是正确的习惯用法,例如a FileWriter和a BufferedWriter包装它.当然,这个问题涉及AutoCloseable包装某些资源的任何情况,而不仅仅是这两个特定的类.
我提出了以下三种选择:
我见过的天真的习惯是只声明ARM管理变量中的顶级包装器:
static void printToFile1(String text, File file) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write(text);
} catch (IOException ex) {
// handle ex
}
}
Run Code Online (Sandbox Code Playgroud)
这很好而且简短,但它已被打破.由于底层FileWriter未在变量中声明,因此永远不会在生成的finally块中直接关闭它.它只能通过close包装方法关闭BufferedWriter.问题是,如果从bw构造函数抛出异常,close则不会调用它,因此底层FileWriter 将不会被关闭.
static void printToFile2(String text, File file) {
try (FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(text); …Run Code Online (Sandbox Code Playgroud) 我想在不删除该文件的当前信息的情况下将新行附加到现有文件.简而言之,这是我使用当前时间的方法:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
Writer output;
output = new BufferedWriter(new FileWriter(my_file_name)); //clears file every time
output.append("New Line!");
output.close();
Run Code Online (Sandbox Code Playgroud)
上述行的问题只是它们删除了我现有文件的所有内容,然后添加了新的行文本.
我想在文件内容的末尾添加一些文本而不删除或替换任何内容.
以下方法仅写出我添加的最新项目,它不会附加到以前的条目.我究竟做错了什么?
public void addNew() {
try {
PrintWriter pw = new PrintWriter(new File("persons.txt"));
int id = Integer.parseInt(jTextField.getText());
String name = jTextField1.getText();
String surname = jTextField2.getText();
Person p = new Person(id,name,surname);
pw.append(p.toString());
pw.append("sdf");
pw.close();
} catch (FileNotFoundException e) {...}
}
Run Code Online (Sandbox Code Playgroud) 我有一个应用程序,它使用简单的套接字在两个系统之间传递一些字符.我把我的java应用程序作为服务器运行.我建立一个连接很好,甚至传递一个消息.但是,在发送一条消息后,我的连接关闭.
从我可以看出它似乎在关闭时printWriter,bufferedReader套接字本身正在关闭?!这很糟糕,因为我有多条消息要在同一个连接上发送.
printWriter = new PrintWriter(theServer.getClientSocket().getOutputStream());
bufferedReader = new BufferedReader(new InputStreamReader(theServer.getClientSocket().getInputStream()));
printWriter.println("the line");
printWriter.close(); //Closing on these lines?
bufferedReader.close(); //Closing on these lines?
Run Code Online (Sandbox Code Playgroud)
我满满的吗?如何在Java中维护此连接?
我正在寻找一种简单易用的解决方案,使用指定的方法将文本附加到Java 8中的现有文件中Charset cs.我在这里找到的解决方案涉及的标准Charset在我的情况下是禁止的.
我用JSch创建了一个SSH客户端.客户端正在使用我的Apache Mina SSH服务器.但是当我使用真实设备进行测试时,它会失败.
这是客户端的代码:
public boolean openConnection() throws ItsSshException {
boolean connectSuccess = false;
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
jschSSH.setConfig(config);
try {
sshSession = jschSSH.getSession(username, hostname, port);
sshSession.setPassword(password);
sshSession.connect(connectionTimeout);
LOGGER.info("Connection timeout : " + connectionTimeout);
Thread.sleep(1000);
sshHChannel = sshSession.openChannel("shell");
sshHChannel.connect();
in = sshHChannel.getInputStream();
out = new PrintStream(sshHChannel.getOutputStream());
clearInitialSocketState();
connectSuccess = true;
} catch (Exception e) {
LOGGER.error("Error during connecting to host: " + hostname +
", port: " + port + "!", e);
throw new ItsSshException("Error during connecting …Run Code Online (Sandbox Code Playgroud) 我使用下面的代码段将文本写入文件的末尾,以便每次调用它.但是,它正在擦除旧数据,然后将新数据写入文件的开头.如何修复下面的代码,以便追加新数据总是在文件的末尾?
public boolean writeToFile(String directory, String filename, String data ){
File out;
OutputStreamWriter outStreamWriter = null;
FileOutputStream outStream = null;
out = new File(new File(directory), filename);
if ( out.exists() == false ){
out.createNewFile();
}
outStream = new FileOutputStream(out) ;
outStreamWriter = new OutputStreamWriter(outStream);
outStreamWriter.append(data);
outStreamWriter.flush();
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个程序,将文本保存在文件上,然后将文本添加到文件中.但是,每次我尝试写入文件时,它都会覆盖它并且不会写任何内容.我需要它来添加我想要的任何信息.
FileReader input;
BufferedReader readFile;
FileWriter output;
BufferedWriter writeFile;
try {
// input = new FileReader(password_file);
//readFile = new BufferedReader(input);
output = new FileWriter(password_file);
writeFile = new BufferedWriter(output);
//while ((temp_user= readFile.readLine()) !=null) {
//temp_pass = readFile.readLine();
//}
temp_user = save_prompt.getText();
temp_pass = final_password;
//Writes to the file
writeFile.write(temp_user);
writeFile.newLine();
writeFile.write(temp_pass);
}
catch(IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud) 在我的在线计算机科学课上,我必须编写一个程序来确定太阳系中每个行星的表面引力.除了一个,我几乎已经完成了它的每个方面.我需要使用单独的方法将表面重力写入文件.这是我目前的方法:
public static void writeResultsToFile(double g) throws IOException{
PrintWriter outFile = new PrintWriter(new File("planetaryData.txt"));
outFile.printf("%.2f%n", g);
outFile.close();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我将它写入文件时,它将覆盖以前的值.我如何获得它包括所有值.如果有帮助,这是我的全部代码:
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.File;
public class gravityV1 {
/**
* @param args
*/
public static double calculateSurfaceGravity(double d, double M){
double G = 6.67 * Math.pow(10, -11);
double r = d;
double g;
g = G * M/Math.pow(r/2*1000, 2);
return g;
}
public static void printResultsToScreen(String planetName, double diameterKm, double massKg, double g){
System.out.printf("%-15s%-17.0f%-17.2e%.2f%n", planetName, diameterKm, massKg, …Run Code Online (Sandbox Code Playgroud) 我有一些中间数据,我需要存储在HDFS和本地.我正在使用Spark 1.6.在HDFS作为中间形式我正在获取数据/output/testDummy/part-00000和/output/testDummy/part-00001.我想使用Java/Scala的地方保存这些分区,这样我可以将它们保存为/users/home/indexes/index.nt(双方在当地的合并),或者/users/home/indexes/index-0000.nt和/home/indexes/index-0001.nt分别.
这是我的代码:注意:testDummy与test相同,输出有两个分区.我想单独存储它们或组合它们但是本地存储index.nt文件.我更喜欢分别存储在两个数据节点中.我正在使用集群并在YARN上提交spark工作.我还添加了一些评论,多少次以及我得到的数据.我该怎么办?任何帮助表示赞赏.
val testDummy = outputFlatMapTuples.coalesce(Constants.INITIAL_PARTITIONS).saveAsTextFile(outputFilePathForHDFS+"/testDummy")
println("testDummy done") //1 time print
def savesData(iterator: Iterator[(String)]): Iterator[(String)] = {
println("Inside savesData") // now 4 times when coalesce(Constants.INITIAL_PARTITIONS)=2
println("iter size"+iterator.size) // 2 735 2 735 values
val filenamesWithExtension = outputPath + "/index.nt"
println("filenamesWithExtension "+filenamesWithExtension.length) //4 times
var list = List[(String)]()
val fileWritter = new FileWriter(filenamesWithExtension,true)
val bufferWritter = new BufferedWriter(fileWritter)
while (iterator.hasNext){ //iterator.hasNext is false
println("inside iterator") //0 times
val …Run Code Online (Sandbox Code Playgroud)