scala读写文件 comparing values of types Unit and Int using `!=' will always yield true

由于scala没有对写入文件的支持,所以写文件时通常借助java进行IO操作

 1 //方式一(小文件)
 2 
 3   /* val s1 = Source.fromFile("D:\\inputword\\hello.txt","GBK");
 4   val buffer = s1.toList.toArray
 5 
 6   val des = new PrintWriter("C:\\Users\\Administrator\\Desktop\\scalatest.txt");
 7 
 8   des.write(buffer,0,buffer.length);
 9   des.flush();
10   des.close();
11   s1.close();
12   */
13 
14   //方式二(大文件)
15   val s2 = Source.fromFile("C:\\Users\\Administrator\\Desktop\\log.data", "UTF-8");
16 
17   val buffer = new Array[Char](1024);
18   val des = new PrintWriter("C:\\Users\\Administrator\\Desktop\\scalatest.txt");
19 
20   val reader = s2.reader();
21 
22   var count: Int = 0;
23 
24   while ({ count = reader.read(buffer); count } != -1) {
25     des.write(buffer, 0, buffer.length);
26   }
27 
28   //错误(comparing values of types Unit and Int using `!=' will always yield true),在java中这么写没问题,但在scala中赋值过程本身返回的是Unit,如果你想这么用,参考上面的while循环,使用赋值语句块即可
29   /*while((count = reader.read(buffer)) != -1) {
30 
31   }*/
32 
33   des.close();
34   des.flush();
35   s2.close();
posted @ 2018-12-17 14:50  tele  阅读(748)  评论(0编辑  收藏  举报