简体   繁体   English

写入 Java WebService 中的文本文件

[英]Write to text file in Java WebService

For school I have to make a webservice as a part of a exercise.对于学校,我必须将 Web 服务作为练习的一部分。 In this program I must use a.txt file which will serve as a database.在这个程序中,我必须使用将用作数据库的.txt 文件。 When I use a BufferedWriter it says that the information is succesfully written to the file.当我使用 BufferedWriter 时,它表示信息已成功写入文件。 But the file is still unchanged.但文件仍然没有改变。 Reading from the file went well.从文件中读取进展顺利。 Thanks in advance!提前致谢!

The code:编码:

    @WebService
public class Vak {

@WebMethod
    public boolean addLesson(String lessonname, double mark){       
        if(!lessonname.equals("") || !(mark == 0.00)){
            try{
                FileInputStream fis = new FileInputStream("C:/marks.txt");
                DataInputStream in = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;         
                while ((strLine = br.readLine()) != null){
                    String [] splitted = strLine.split(" ");
                    if(splitted[0].equalsIgnoreCase(lessonname)){
                        System.out.println("Lesson already exists");
                        return false;
                    }
                }           
                BufferedWriter out = new BufferedWriter(new FileWriter("C:/marks.txt", true));
                out.newLine();
                out.write(lessonname + " " + mark);
                return true;
            }
            catch(Exception e){
                System.out.println("Exception " + e);
                return false;
            }
        }   
        return false;
    }
}

Add添加

out.close();

before you return true;在您return true;

From the documentation , the close method does the following:文档中, close方法执行以下操作:

Closes the stream, flushing it first.关闭 stream,先冲洗它。 Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown.一旦 stream 被关闭,进一步的 write() 或 flush() 调用将导致抛出 IOException。 Closing a previously closed stream has no effect.关闭之前关闭的 stream 无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM