Вот некоторые из возможных способов создания и записи файла в Java:
Использование FileOutputStream
try {
File fout = new File("myOutFile.txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("Write somthing to the file ...");
bw.newLine();
bw.close();
} catch (FileNotFoundException e){
// File was not found
e.printStackTrace();
} catch (IOException e) {
// Problem when writing to the file
e.printStackTrace();
}
Использование FileWriter
try {
FileWriter fw = new FileWriter("myOutFile.txt");
fw.write("Example of content");
fw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
Использование PrintWriter
try {
PrintWriter pw = new PrintWriter("myOutFile.txt");
pw.write("Example of content");
pw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
Использование OutputStreamWriter
try {
File fout = new File("myOutFile.txt");
FileOutputStream fos = new FileOutputStream(fout);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("Soe content ...");
osw.close();
} catch (FileNotFoundException e) {
// File not found
e.printStackTrace();
} catch (IOException e) {
// Error when writing to the file
e.printStackTrace();
}
Для дополнительной проверки этого руководства о том, как читать и записывать файлы в Java .
class A
{
private $b = 'c';
}
$obj = new A();
$r = new ReflectionObject($obj);
$p = $r->getProperty('b');
$p->setAccessible(true); // <--- you set the property to public before you read the value
var_dump($p->getValue($obj));
getProperty
генерирует исключение, а не ошибку. Значимость заключается в том, что вы можете справиться с этим и сохранить себя if
:
$ref = new ReflectionObject($obj);
$propName = "myProperty";
try {
$prop = $ref->getProperty($propName);
} catch (ReflectionException $ex) {
echo "property $propName does not exist";
//or echo the exception message: echo $ex->getMessage();
}
Чтобы получить все частные свойства, используйте $ref->getProperties(IS_PRIVATE);
IS_PRIVATE
должна быть ReflectionProperty::IS_PRIVATE
– Nicola Pedretti
25 January 2018 в 00:03
private
видны только для классов, в которых они были созданы. Но в этом случаеhasProperty
вернетfalse
– zerkms 23 July 2012 в 00:59$p = $r->getParentClass()->getProperty('b');
– AlexandrX 28 May 2017 в 05:11