image.png
availble() 這個INPUT還有多少東西可以讀听隐。但是這個值不是準確的值织咧,不能做嚴謹的操作。
image.png
read() 為啥不是返回BYTE 而是 INT懦底?
因為如果READ到頭了唇牧,可以返回-1
read(byte[]) 盡量把BYTE Array 填滿
public static void main(String[] args) throws IOException {
FileOutputStream out = null;
try (FileInputStream in = new FileInputStream("a.txt")){
out = new FileOutputStream("b.txt");
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
out.write(c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
}
public static void main(String[] args) throws IOException {
try (FileInputStream in = new FileInputStream("a.txt")){
byte[] bytes = new byte[700];
int n = in.read(bytes);
System.out.println("n = " + n);
for (byte b : bytes) {
System.out.print((char)b);
}
}
}
image.png
如果要讀中文,需要用file reader & file writer ; 因為他是16位16位讀的聚唐。
unicode 是16位丐重, 2^16
public static void main(String[] args) throws IOException {
try (FileReader in = new FileReader("a.txt")){
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
}
}
image.png
public static void main(String[] args) throws IOException {
try(InputStreamReader cin = new InputStreamReader(System.in)) {
System.out.println("Enter char, 'q' to quit.");
StringBuffer userInput = new StringBuffer();
while (true) {
char c = (char) cin.read();
if (c == 'q') break;
userInput.append(c);
}
System.out.println(userInput);
}
}
image.png
public static void main(String[] args) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt")))){
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
class MyBufferedReader {
private FileInputStream in;
private StringBuffer buffer;
public MyBufferedReader(FileInputStream in) {
this.in = in;
buffer = new StringBuffer();
}
public String nextLine() throws IOException {
while (true) {
int c = in.read();
if (c == -1 || c == '\n') break;
buffer.append((char) c);
}
String output = buffer.toString();
buffer = new StringBuffer();
return output;
}
}
鍵盤按行讀
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String line = scanner.nextLine();
if (line.toLowerCase().equals("exit"))
break;
System.out.println("Input text : " + line);
}
}
image.png
public static void main(String[] args) {
String dirname = "F:/";
File d = new File(dirname);
String[] path = d.list();
for (String p : path) {
System.out.println(p);
}
}