现在的位置: 首页 > 综合 > 正文

IO笔记

2013年01月11日 ⁄ 综合 ⁄ 共 6417字 ⁄ 字号 评论关闭

FilenameFilter用法:

public static void main(String[] args) {
  File path = new File("G://programs//java//ConsoleDatabase");
  final String regex="//D*[.]?jpx//D*";
  String[] list;
  //if (args.length == 0)
   //list = path.list();
  //else
   list = path.list(new FilenameFilter(){
    private Pattern pattern = Pattern.compile(regex);
    @Override
    public boolean accept(File dir, String name) {
     return pattern.matcher(name).matches();
    }
    
   });
  Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
  for (String dirItem : list)
   System.out.println(dirItem);
  
  File
  old = new File("c://wepkeys.txt"),
  rname = new File("c://ConsoleDatabase.jpx");
  old.renameTo(rname);
 }

 

=========================================================

 

Java has System.in, System.out, and System.err. Throughout this book, you’ve seen how to write to standard output using System.out, which is already pre-wrapped as a PrintStream object. System.err is likewise a PrintStream, but System.in is a raw InputStream with no wrapping. This means that although you can use System.out and System.err right away, System.in must be wrapped before you can read from it.

 

setIn(InputStream)
setOut(PrintStream)
setErr(PrintStream)

 

public class Redirecting {
public static void main(String[] args)
throws IOException {
PrintStream console = System.out;
BufferedInputStream in = new BufferedInputStream(
new FileInputStream("Redirecting.java"));
PrintStream out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("test.out")));
System.setIn(in);
System.setOut(out);
System.setErr(out);
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String s;
while((s = br.readLine()) != null)
System.out.println(s);
out.close(); // Remember this!
System.setOut(console);
}
}

 

====================================================

 

new IO:

public static void main(String[] args) throws Exception {
if(args.length != 2) {
System.out.println("arguments: sourcefile destfile");
System.exit(1);
}
FileChannel
in = new FileInputStream(args[0]).getChannel(),
out = new FileOutputStream(args[1]).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
while(in.read(buffer) != -1) {
buffer.flip(); // Prepare for writing
out.write(buffer);
buffer.clear(); // Prepare for reading
}
}

 

 

 

Memory-mapped files:

static void mappedFile() throws IOException{
  int length=10;
  MappedByteBuffer out=new RandomAccessFile(fileName,"rw").getChannel()
        .map(FileChannel.MapMode.READ_WRITE, 0, length);
  for(int i = 0; i < length; i++)
   out.put((byte)'x');
   System.out.println("Finished writing");
   for(int i = length/2; i < length/2 + 6; i++)
    System.out.println((char)out.get(i));
 }

 

File locking:

public class LockingMappedFiles {
static final int LENGTH = 0x8FFFFFF; // 128 MB
static FileChannel fc;
public static void main(String[] args) throws Exception {
fc =
new RandomAccessFile("test.dat", "rw").getChannel();
MappedByteBuffer out =
fc.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
for(int i = 0; i < LENGTH; i++)
out.put((byte)’x’);
new LockAndModify(out, 0, 0 + LENGTH/3);
new LockAndModify(out, LENGTH/2, LENGTH/2 + LENGTH/4);
}
private static class LockAndModify extends Thread {
private ByteBuffer buff;
private int start, end;
LockAndModify(ByteBuffer mbb, int start, int end) {
this.start = start;
this.end = end;
mbb.limit(end);
mbb.position(start);
buff = mbb.slice();
start();
}
public void run() {
try {
// Exclusive lock with no overlap:
FileLock fl = fc.lock(start, end, false);
System.out.println("Locked: "+ start +" to "+ end);
// Perform modification:
while(buff.position() < buff.limit() - 1)
buff.put((byte)(buff.get() + 1));
fl.release();
System.out.println("Released: "+start+" to "+ end);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}

 

=====================================================

 

JAR 命令:

 

Here are some typical ways to invoke jar. The following command creates a JAR file called myJarFile.jar that contains all of the class files in the current directory, along with an automatically generated manifest file:
jar cf myJarFile.jar *.class

The next command is like the previous example, but it adds a user-created manifest file called myManifestFile.mf:
jar cmf myJarFile.jar myManifestFile.mf *.class

This produces a table of contents of the files in myJarFile.jar:
jar tf myJarFile.jar

This adds the "verbose" flag to give more detailed information about the files in myJarFile.jar:
jar tvf myJarFile.jar

Assuming audio, classes, and image are subdirectories, this combines all of the subdirectories into the file myApp.jar. The "verbose" flag is also included to give extra feedback while the jar program is working:
jar cvf myApp.jar audio classes image

==========================================================

对象序列中,static字段需要手动序列化!

 

深拷贝:

public static void copyObj() throws IOException,ClassNotFoundException{
  House house = new House();
  List<Animal> animals = new ArrayList<Animal>();
  animals.add(new Animal("Bosco the dog", house));
  animals.add(new Animal("Ralph the hamster", house));
  animals.add(new Animal("Molly the cat", house));
  //print("animals: " + animals);
  ByteArrayOutputStream buf1 =new ByteArrayOutputStream();
  ObjectOutputStream o1 = new ObjectOutputStream(buf1);
  o1.writeObject(animals);
  o1.writeObject(animals); // Write a 2nd set
  // Write to a different stream:
  
  ObjectInputStream in1 = new ObjectInputStream(
    new ByteArrayInputStream(buf1.toByteArray()));
  
  List
  animals1 = (List)in1.readObject(),
  animals2 = (List)in1.readObject();
  
  System.out.println("animals1: " + animals1);
  System.out.println("animals2: " + animals2);
 }

 

==================================================

 

Preferences:

public class PreferencesDemo {
public static void main(String[] args) throws Exception {
Preferences prefs = Preferences
.userNodeForPackage(PreferencesDemo.class);
prefs.put("Location", "Oz");
prefs.put("Footwear", "Ruby Slippers");
prefs.putInt("Companions", 4);
prefs.putBoolean("Are there witches?", true);
int usageCount = prefs.getInt("UsageCount", 0);
usageCount++;
prefs.putInt("UsageCount", usageCount);
for(String key : prefs.keys())
print(key + ": "+ prefs.get(key, null));
// You must always provide a default value:
print("How many companions does Dorothy have? " +
prefs.getInt("Companions", 0));
}
}

 

Here, userNodeForPackage( ) is used, but you could also choose systemNodeForPackage( ); the choice is somewhat arbitrary, but the idea is that "user" is for individual user preferences, and "system" is for general installation configuration. Since main( ) is static, PreferencesDemo.class is used to identify the node, but inside a nonstatic method, you’ll usually use getClass( ). You don’t need to use the current class as the node identifier, but that’s the usual practice.

There’s no local file that appears after the program is run the first time. The Preferences API uses appropriate system resources to accomplish its task, and these will vary depending on the OS. In Windows, the registry is used (since it’s already a hierarchy of nodes with key-value pairs). But the whole point is that the information is magically stored for you so that you don’t have to worry about how it works from one system to another.

抱歉!评论已关闭.