|
Эта подсказка показывает, как читать текстовый файл с банком.
[ReadFromJar.java]
import java.applet.*;
import java.io.*;
public class ReadFromJar extends Applet{
public void init(){
readTextFromJar("datafile1.txt");
readTextFromJar("test/datafile2.txt");
}
public void readTextFromJar(String s) {
String thisLine;
try {
InputStream is = getClass().getResourceAsStream(s);
BufferedReader br = new BufferedReader
(new InputStreamReader(is));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Создайте 2 файлов данных.
datafile1.txt в том же каталоге, ReadfromJar.class и datafile2.txt в подкаталог с именем испытаний
[datafile1.txt]
datafile1 line 1
datafile1 line 2
datafile1 line 3
datafile1 line 4
datafile1 line 5
[test\datafile2.txt]
datafile2 line 1
datafile2 line 2
datafile2 line 3
datafile2 line 4
datafile2 line 5
Создание банка с
jar cf readjar.jar ReadFromJar.class datafile1.txt test\datafile2.txt
Попробуйте с follwing страницу HTML
<HTML><HEAD></HEAD><BODY>
<APPLET CODE=ReadFromJar.class width=1 height=1 archive=readjar.jar>
</APPLET>
See java console for output</BODY></HTML>
|
|
|
Этот совет Java показано, как проверить, существует ли файл.
import java.io.*;
public class FileTest {
public static void main(String args[]) {
File f = new File(args[0]);
System.out.println
(f + (f.exists()? " is found " : " is missing "));
}
}
|
|
|
Этот совет Java демонстрирует метод копирования одного файла в другой файл. Разработчик может использовать файловые потоки, чтобы скопировать содержимое файла.
// Copy the source file to target file.
// In case the dst file does not exist, it is created
void copy(File source, File target) throws IOException {
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
|
|
|
Этот совет будет показать возможности доступа к данным наугад. Реальное преимущество случайного доступа к файлам является как следует из их названия, как только их открытии, они могут быть прочитаны или записываются в случайном порядке, просто используя номер записи или вы можете добавить в конец поскольку вы будете знать, сколько записей в файле.
import java.io.File;
import java.io.RandomAccessFile;
import java.io.IOException;
public class DemoRandomAccessFile {
private static void doAccess() {
try {
File file = new File("DemoRandomAccessFile.out");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// Read a character
byte ch = raf.readByte();
System.out.println("Read first character of file: " + (char)ch);
// Now read the remaining portion of the line.
// This will print out from where the file pointer is located
// (just after the '+' character) and print all remaining characters
// up until the end of line character.
System.out.println("Read full line: " + raf.readLine());
// Seek to the end of file
raf.seek(file.length());
// Append to the end of the file
raf.write(0x0A);
raf.writeBytes("This will complete the Demo");
raf.close();
} catch (IOException e) {
System.out.println("IOException:");
e.printStackTrace();
}
}
public static void main(String[] args) {
doAccess();
}
}
}
|
Вывод:
Read first character of file: R
Read full line: ohit Khariwal Mohit Parnami
И вот оно DemoRandomAccesFile.out файла.
Rohit Khariwal Mohit Parnami
This will complete the Demo
|
|
Чтение текста со стандартного ввода, можно сделать следующим образом:
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String str = "";
while (str != null) {
System.out.print("$bash> ");
str = in.readLine();
process(str);
}
} catch (IOException e) {
}
|
|
|
Запись в файл в Java можно сделать следующим образом:
try {
BufferedWriter out = new BufferedWriter(
new FileWriter("outfilename"));
out.write("aString");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
|
|
|
Поскольку Java являются строки в кодировке Юникод, вы должны указана другая кодировка при печати на консоль DOS. Это делается через класс OutputStreamWriter.
import java.io.*;
public class DosString {
public static void main(String args[]){
String javaString =
"caractères français : à é \u00e9"; // Unicode for "é"
try {
// output to the console
Writer w =
new BufferedWriter
(new OutputStreamWriter(System.out, "Cp850"));
w.write(javaString);
w.flush();
w.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Альтернативой является начало JVM и передать в командной строке по умолчанию кодировку файла будет использоваться. Тогда вы сможете использовать регулярные System.out.println ().
javac MyApp.java
java -Dfile.encoding=Cp850 MyApp
Альтернативная техника
import java.io.*;
public class test {
public static void main(String[] args) {
PrintStream ps = null;
String javaString =
"caractères français : à é \u00e9"; // Unicode for "é"
try {
ps = new PrintStream(System.out, true, "Cp850");
} catch (UnsupportedEncodingException error) {
System.err.println(error);
System.exit(0);
}
ps.println(javaString);
}
}
|
|
|
Вы можете получить список дисков системы с помощью listRoots () Метод файла класса:
File[] roots = File.listRoots();
for(int i=0;i<roots.length;i++)
System.out.println("Root["+i+"]:" + roots[i]);
|
|
|
Чтение текста из файла можно сделать следующим образом:
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
|
|
|
Сериализация / десериализации объектов очень полезна, если вы хотите использовать объект Java в будущем. Следующий код показывает, как для сериализации объектов.
Object object = new String("Hello World");
try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
|
|